前端试题-如何居中一个float:left的元素

有时我们给两个元素添加float:left让其处于同一水平线上,又想让它们有一个整体居中的效果。

可以给它们外面包个div,父元素设置position:relative;float:left;left:50%;子元素设置position:relative;float:left;left:-50%(right:50%也可以).

在下面例子里,父元素相对定位,左浮动,并且left:50%,这样参考点就从文档左上角变成了中间50%那点。

给子元素相对定位,是想将相对于父元素来定位自己的位置,float:left让子元素在同一水平线上显示,left:-50%是因为子元素的整体宽度就是父元素的宽度,left:50%就是让子元素内容往相对父元素左上那一点往左移动父元素一半的宽度(right:50%是距右边50%,效果一样),正好实现子元素内容居中显示的效果。

<!DOCTYPE html>
<html>
<head>
    <meta charset = "utf-8">
    <style type="text/css">
        .p {QQ截图20160221190858
            position : relative;
            float : left;
            left : 50%;
            background:gray;
            border:4px solid red;
        }
        .c {
            position : relative;
            float : left;
            left : -50%;
            background:pink;
        }
    </style>

</head>
<body>
    <div class="p">
        <div class="c">oooooooooooooooo</div>
        <div class="c">hhhhhhhhh</div>
    </div>
</body>
</html>

原文地址:https://www.cnblogs.com/sunshinegirl-7/p/5205407.html