css垂直居中

行内 inline 元素: line-height 的值等于height的值;
absolute 定位元素:
1. top:50% +margin-top的赋值(当前元素高度的一半);
2.transform: translate(-50%.-50%);
3.top,left,bottom,right 均为0 + margin:auto;

 <style>
     .box{
         height: 100px;
         border: 1px solid #ccc;
         margin: 30px 0;
     }
     .item{
         background-color: #ccc;
     }
     /* 行内 inline 元素 */
     .box-1{
        text-align: center;
        line-height: 100px;
     }
     /* absolute 定位元素 top:50% +margin-top的赋值 需要知道具体宽高 */
     .box-2{
         position: relative;
     }
     .box-2 .item{
         position: absolute;
         left: 50%;
         top: 50%;
         margin-top: -25px;
         margin-left: -100px;
         width: 200px;
         height: 50px;
     }
     /* transform: translate(-50%,-50%) 兼容的问题(可不用知道具体宽高)*/
     .box-3{
         position: relative;
     }
     .box-3 .item{
         position: absolute;
         left: 50%;
         top: 50%;
         width: 200px;
         height: 50px;
         transform: translate(-50%,-50%)
     }
     /* top,left,bottom,right 均为0 */
     .box-4{
         position: relative;
     }
     .box-4 .item{
         position: absolute;
         width: 200px;
         height: 50px;
         left: 0;
         top: 0;
         bottom: 0;
         right: 0;
         margin: auto;
     }
 </style>
 <!-- 行内 inline 元素 -->
 <div class="box box-1">
     <span> 行内 inline 元素</span>
 </div>
 <!-- absolute 定位元素 top:50% +margin-top的赋值  -->
 <div class="box box-2">
    <div class="item">top:50% +margin-top的赋值</div>
</div>
<!-- absolute 定位元素  transform: translate(-50%.-50%) -->
<div class="box box-3">
    <div class="item">transform: translate(-50%.-50%)</div>
</div>

<!-- absolute 定位元素  top,left,bottom,right 均为0 -->
<div class="box box-4">
    <div class="item">top,left,bottom,right 均为0</div>
</div>

···

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容