How to center a floating element

Method a: Add a parent to the floating element

<style type="text/css">
        .con {
            position: relative;
            float: left;
            left: 50%;
            background: rgb(5, 175, 231);
        }
        .box {
            position: relative;
            float: left;
            left: -50%;
            width: 100px;
            height: 100px;
            background: lightcoral;
        }
    </style>
    <body>
        <div class="con">
            <div class="box"></div>  
        </div>
    </body>

Blue con brick red box "Daddy," we can clearly see from the chart, positioned to the left of the con by 50 percent. By the relative positioning of the box, positioned in place of 50% con, namely positive center.

To sub-elements relative positioning is relative to the parent element will want to locate their position, float: left to let the child element at the same level display, left: -50% due to the overall width is the width of a child element of the parent element, left : 50% is to let the child element content relative to the upper left of the parent element that moved a little to the left half of the width of the parent element (right: 50% to 50% is from the right, the same effect), just to achieve sub-element content of effect centered.

 

Guess you like

Origin www.cnblogs.com/ganiner/p/11518289.html