您的位置:首页 > Web前端 > CSS

[置顶] CSS3清除浮动 保持浮层水平垂直居中

2016-11-26 14:41 253 查看
1)清除浮动,什么时候需要清除浮动,清除浮动都有哪些方法

    1、在非IE浏览器(如Firefox)下,当容器的高度为auto,且容器的内容中有浮动(float为left或right)的元素,在这种情况下,容器的高度不能自动伸长以适应内容的高度,使得内容溢出到容器外面而影响(甚至破坏)布局的现象。这个现象叫浮动溢出,为了防止这个现象的出现而进行清除浮动。

    2、清除浮动的方法:

        (1)使用clear:both。如果我们明确的知道紧接着浮动元素后面的元素,可以使用这种方法来清除浮动。这种方法简单,容易使用,不需要hack,语义化也不错。

        (2)空div方法。这个方法一般是不推荐使用的,虽然没有什么副作用的,但因为这个div纯粹是为了表现,没有语义。

        (3)对容器添加clearfix类会清除浮动

        .clearfix:after {

            visibility: hidden;

            display: block;

            font-size: 0;

            content: " ";

            clear: both;

            height: 0;

        }

2)如何保持浮层水平垂直居中

    a.利用flexbox布局

        .parent{

            width: 100%;

            height: 37.5rem/* 600px */;

            background: #09c;

            display: flex;

            justify-content:center;     /* 水平居中 */

            align-items:center;         /* 垂直居中 */

            /* flex-direction:column; */    /* 一列显示 */

        }

        .children{

            width: 100px;

            height: 100px;

            background-color: #eee;

            border: 1px dashed #000;

            margin: 5px;

            /*如果children下面还有子元素的话,可以嵌套使用*/

            /* display: flex;

            justify-content: center;

            align-items:center;  */

        }

    b.利用绝对定位与transform

        .parent{

            position: absolute;

            background-color: #eee;

            width: 100%;

            height: 100%;

        }

        .parent .children{

            background-color: #751;

            width: 200px;

            height: 200px;

            position: absolute;

            top: 50%;

            left: 50%;

            -webkit-transform: translate(-50%,-50%);

        }

    c.将父元素定位,子元素绝对定位,利用margin负值为子元素宽高的一半来实现。

        .parent{

            position: relative;

            background-color: #eee;

            height: 600px;

            width: 100%;

        }

        .parent .children{

            background-color: #751;

            width: 200px;

            height: 200px;

            position: absolute;

            top: 50%;

            left: 50%;

            margin: -100px 0 0 -100px;

        }

    d.利用定位与margin:auto

        .parent{

            width: 100%;

            height: 37.5rem/* 600px */;

            background: #09c;

            position: relative;

        }

        .children{

            width: 100px;

            height: 100px;

            background-color: #eee;

            position: absolute;

            top: 0;

            left: 0;

            bottom: 0;

            right: 0;

            margin: auto;

        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: