Html/CSS06(定位,居中)

今天是2018年7月16日

1.相对定位

给元素设置position: relative;可以使元素处于相对定位中。

<style>
        /* 相对定位就是元素在页面上正常的位置 */
        div{
            width: 100px;
            height: 100px;
            background-color: red;
            position: relative;
            top: 0px;
            left:0px;
            /* 相对定位一般不适用right/bottom */
            right: 0px;
            bottom: 0px;
        }
    </style>

2.绝对定位

不同于相对定位,绝对定位是指在父元素中绝对的位置

<style>
        .parent{
            width: 200px;
            height: 200px;
            background-color: red;
            position: relative;
        }
        .child{
            width: 50px;
            height: 50px;
            background-color: blue;
            position: absolute;
            right: 0;
        }
    </style>

3.元素的垂直水平居中

利用绝对定位和相对定位,可以实现元素在父类中的水平垂直居中

原理是使父元素相对定位,子元素绝对定位,给子元素50%定位后利用margin-top和margin-left回移子元素width和height属性的一半。

<style>
        *{padding: 0;margin: 0}
        .parent{
            width:300px;
            height: 300px;
            background-color: red;
            position: relative;
        }
        .child{
            width: 50px;
            height: 50px;
            position: absolute;
            left: 50%;
            top: 50%;
            background-color: blue;
            margin-top: -25px;
            margin-left: -25%;
        }
    </style>

4.固定定位

固定定位可以使元素不受到滚动条的影响,始终固定在某一个位置

    <style>
        body{
            line-height: 30px;
        }
        div{
            width: 20px;
            height: 50px;
            background: tomato;
            position: fixed;
            right: 10px;
            bottom: 500px;
        }
    </style>

5.Z-index

给元素设置z-index值可以更改元素覆盖情况下的优先显示顺序

<style>
        .parent{
            width: 300px;
            height: 300px;
            background-color: red;
            position: relative;
        }
        .one{
            width: 100px;
            height: 200px;
            background-color: green;
            position: absolute;
            z-index: 2;
        }
        .two{
            width: 200px;
            height: 100px;
            background-color: blue;
            position: absolute;
            z-index: 3;
        }
        .parent:hover .one{
            z-index:20;
        }
    </style>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,702评论 1 92
  • 学会使用CSS选择器熟记CSS样式和外观属性熟练掌握CSS各种选择器熟练掌握CSS各种选择器熟练掌握CSS三种显示...
    七彩小鹿阅读 11,449评论 2 66
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 28,415评论 1 45
  • CSS 是什么 css(Cascading Style Sheets),层叠样式表,选择器{属性:值;属性:值}h...
    崔敏嫣阅读 5,368评论 0 5
  • 1.CSS基本概念 1.1 CSS的定义 CSS(Cascading Style Sheets)层叠样式表,主要用...
    寥寥十一阅读 5,942评论 0 6

友情链接更多精彩内容