[CSS]水平垂直居中方案

简单总结一下常用的水平垂直居中方案

 

直接在父级元素设置 text-alignline-height ,针对未浮动的行内元素

1 <div class="box">2 <span class="item">我是span标签</span>3 </div>
1 .box {2  width: 600px;3  height: 400px;4  margin: 50px auto;5  border: 1px solid red;6 7  line-height: 400px;8  text-align: center;9 }

 

在父级设置 line-height ,在本身设置 margin 值和 transform 属性,针对已浮动的行内元素

1 .item {2  float: left;3  margin-left: 50%;4  transform: translateX(-50%);5 }

  

通过定位,这种方案是比较常用的手段,不区分是否浮动,前提是父级有宽高。

  块级元素在父级设置 position: relative;

1 .box {2  width: 600px;3  height: 400px;4  margin: 50px auto;5  border: 1px solid red;6  position: relative;7 }

  在本身设置 position: absolute;

 1 .item { 2  display: block;  3  width: 100px; 4  height: 100px; 5  color: white; 6  background: #000; 7  8 /* 方案一 */ 9  position: absolute;10  left: 50%;11  top: 50%;12  margin-left: -50px; /* 值为本身宽度的一半 */13  margin-top: -50px; /* 值为本身高度的一半 */14 /* transform: translate(-50%, -50%); 可以代替margin,IE9以下不支持 */15 16 /* 方案二 */17  top: 0;18  left: 0;19  bottom: 0;20  right: 0;21  margin: auto; 22 }

  

  行内元素,父级设置和上面一样,本身设置如下:

1 .item {2  position: absolute;3  position: absolute;4  left: 50%;5  top: 50%;6  transform: translate(-50%, -50%);7 }

 

推荐方案:flex布局

 1 .box { 2  width: 600px; 3  height: 400px; 4  margin: 50px auto; 5  border: 1px solid red; 6  7  display: flex; 8  justify-content: center; 9  align-items: center;10 }

 

相关文章