怎么让浮动的元素和定位的元素水平垂直居中

浮动元素水平居中:

1.如果浮动元素定宽,可以设置margin:0 auto居中

2.如果浮动元素不定宽,在外层包裹一个div .wrap {position:relative;//为了让元素可以偏移float:left;//让元素具有宽度,利用BFC元素特性 left:50%;} .content{position:relative;float:left;right:50%;},由于.wrap也浮动,为了不影响其他元素,需要清除浮动

<div class="wrap">
<div class="content">123</div>
</div>
    .content {
    width: 100px;
    height: 100px;
    background-color: #e92322;
    float: left;
    position: relative;
    left: -50%;
} .wrap { float: left; position: relative; left: 50%; }

 浮动元素垂直居中:

  核心代码: vertical-align: middle;display: table-cell;

<style type="text/css">
    #demo {
        width: 300px;
        height: 200px;
        background-color: grey;

        display: table-cell;
        vertical-align: middle;
    }
        .fl {

            float: left;
            width: 50px;
            height: 50px;
            background-color: black;

        }
    </style>
<body>
    <div id="demo">
        <div class="fl"></div>
    </div>
</body>

绝对定位元素水平垂直居中:

left:50%,然后往左走自己盒子的一半(margin-left)

top:50%,然后往上走自己盒子的一半(margin-top)

原文地址:https://www.cnblogs.com/zmshare/p/6172033.html