如何水平垂直居中一个设置了浮动的元素

浮动元素水平居中:

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

#container{  
  width:400px;  
  height:110px;  
  border:1px solid black;  
}  
.content{  
   width:100px; /*设置同内容元素相同宽度*/
   margin: 0 auto;  
}  
.content div{  
  width:100px;  
  height:100px;  
  float:left;  
}

<div id="container">  
  <div class="content">  
    <div class="left">left</div>  
  </div>  
</div> 

2.先设置它的 margin-left:50%,这个时候元素的左边缘正好位于其父元素的中央,然后设置其position:relative;left:负本元素宽度的一半,这样的目的是将本元素向左移动其宽度的一半,这个时候可保证本元素的中间点位于父元素的中央。

<!DOCTYPE html>
<html>
<head>
    <title>居中一个浮动元素</title>
    <style type="text/css">
        .content{
            height: 500px;
            width: 500px;
            border: 1px solid red;
        }
        .left{
            height:100px;
            width: 100px;
            border: 1px dashed blue;
            float: left;
            /*水平居中*/
            margin-left: 50%;
            position: relative;
            left: -50px;

        }
    </style>
</head>
<body>
    <div class="content">
        <div class="left"></div>
    </div>
</body>
</html>

二、如果浮动元素不定宽
如果浮动元素不定宽,在外层包裹一个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>

猜你喜欢

转载自www.cnblogs.com/web-record/p/9143887.html