码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-02-21 12:21:44      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:body   wrapper   relative   cond   pos   line   其他   继承   transform   

  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>

 

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

标签:body   wrapper   relative   cond   pos   line   其他   继承   transform   

原文地址:https://www.cnblogs.com/paradise-zzz/p/8456399.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!