关于元素居中之我见(干货)

  1. 不使用定位

    水平居中:text-align = center;(可继承)

    竖直居中:margin:0 auto;(块级元素)

    其他居中:1.文字居中:父元素设置高 子元素设置高  line-height=height(父元素)

            2.图片居中:  vertical-aign:middle ;  <-- 必须放在图片元素中

1   .first{
2     width: 300px;
3     height: 100px;
4     background-color: black;
5     color: white;
6     text-align: center;
7     margin: 0 auto; //针对块级元素
8 
9   }
1   <div class="first">
2     不使用定位(1)
3   </div>
  .second{
    width: 300px;
    height: 100px;
    background-color: green;
  }
  .s_child{
    width: 150px;
    line-height: 100px;
  }
  <div class="second">
    <div class="s_child">
      不使用定位(2)
    </div>
  </div>

  2.定位居中

   a.父元素高度固定     

    父元素:相对定位

    子元素:绝对定位

        top:50%(父元素高度的一半)

        left:50%

        margin-top:自己的高度一半;(加负号)

        margin-left:自己宽度的一半;(加负号)

.dw_one{
      width: 600px;
      height: 300px;
      position: absolute;
      background: black;

    }
    .dw_one_child{
      background: white;
      position: relative;
      width: 50px;
      height: 50px;
      top: 50%;
      left: 50%;
      margin-top: -25px;
      margin-left: -25px;
    }
  <div class="dw_one">
    <div class="dw_one_child">
      a
    </div>
  </div>

    b.父元素高度不固定

  .wrapper{
      width: 600px;
      height: 600px;
    }
    .dw_two{
      width: 100%;
      height: 100%;
      position: absolute;
      background: black;

    }
    .dw_two_child{
      background: white;
      position: relative;
      top: 50%;
      left: 50%;
      width: 100px;
      height: 100px;
      transform:translate(-50%, -50%);
      -moz-transform:translate(-50%, -50%);
      -ms-transform:translate(-50%, -50%);
      -o-transform:translate(-50%, -50%);
      -webkit-transform:translate(-50%, -50%);
    }
1 <div class="wrapper">
2   <div class="dw_two">
3       <div class="dw_two_child">
4         a
5       </div>
6   </div>
7 </div>
 

   3.关于多行文本的居中

    使用display:table; display:table-cell;

    vertical-align:middle; 居中

 1   #outer{
 2            width: 200px;
 3            height: 200px;
 4            background: #cccccc;
 5            display: table;
 6            _position: relative;   // "_"为了兼容IE6
 7        }
 8        #inner{
 9            display: table-cell;
10            vertical-align: middle;
11            _position: absolute;
12            _top: 50%;
13        }
14        #content{
15            _position: relative;
16            _top: -50%;
17        }
1 <div id="outer">
2     <div id="inner">
3         <div id="content">
4           Paradise_追逐者所写的居中问题总结之我见
5         </div>
6     </div>
7 </div>

 

posted @ 2018-02-21 11:33  Paradise_追逐者  阅读(221)  评论(0编辑  收藏  举报