天天看點

css 元素水準垂直居中

總結

1、元素已知寬高: position(left:50%,top:50%) + margin移動50%

2、元素未知寬高: position(left:50%,top:50%) + transform(translate(-50%,-50%))

3、元素未知寬高: position(left:0,top:0,right:0,bottom:0) + margin:auto

4、元素未知寬高(flex布局):父元素設定屬性, display: flex; justify-content: center; align-items: center;

5、元素未知寬高(table-cell布局):

父元素設定為display:table

中間層為display:table-cell; vertical-align: middle;text-align: center;

内層為display:inline-block;

方法一 元素已知寬高 position+margin,移動50%

  • 父元素設定為:position: relative;
  • 子元素設定為:position: absolute; 距上50%,據左50%,然後減去元素自身寬高距離的一半就可。
<div class="box">
    <div class="content"></div>
</div>

.box {
    background-color: #FF8C00;
    width: 300px;
    height: 300px;
    position: relative;
}
.content {
    background-color: #F00;
    width: 100px;
    height: 100px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin: -50px 0 0 -50px;
}

           

方法二 元素未知寬高 position+margin:auto

  • 父元素設定為:position: relative;
  • 子元素設定為:position: absolute; 距上0,距下0,距左0,距右0,然後margin:auto即可
<div class="box">
     <div class="content"></div>
</div>

.box{
   width:500px;
   height: 400px;
   position: relative;
   border:1px solid #000;
}
.content{
   width: 50px;
   height: 50px;
   position: absolute;
   top: 0;
   left: 0;
   right: 0;
   bottom: 0;
   margin: auto;
   background: red;
}
           

方法三 position + transform 元素未知寬高

<div class="box">
    <div class="content">
    </div>
</div>

.box {
    background-color: #FF8C00;
    width: 300px;
    height: 300px;
    position: relative;
}
.content {
    background-color: #F00;
    width: 100px;
    height: 100px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}

           

方法四 flex布局

<div class="box">
    <div class="content"></div>
</div>

.box {
    background-color: #FF8C00;
    width: 300px;
    height: 300px;
    display: flex;//flex布局
    justify-content: center;     //使子項目水準居中
    align-items: center;     //使子項目垂直居中
}
.content {
    background-color: #F00;
    width: 100px;
    height: 100px;
}

           

方法五 table-cell布局

因為table-cell相當于表格的td,td為行内元素,無法設定寬和高,是以嵌套一層,嵌套一層必須設定display: inline-block;

  • 設定外圍為display:table
  • 設定中間層為display:table-cell; (使用這個,則預設内部元素為inline元素,而inline沒有高度,是以内部嵌套層必須設定display:inline-block)
  • 設定内層為display:inline-block;
<div class="box">
    <div class="content">
		<div class="inner"></div>
	</div>
</div>

.box {
    background-color: #FF8C00; 
	width: 300px;
	height: 300px;
	display: table;   /*第一步,table*/
}

.content {
	background-color: #F00; 
	display: table-cell;   /*第二步,table-cell*/
	vertical-align: middle;  /*垂直居中*/
	text-align: center;      /*水準居中*/
}

.inner {
	background-color: #000; 
	display: inline-block;   /*設定為行内塊級元素*/
	width: 20%;
	height: 20%;
}
           
參考連結 https://blog.csdn.net/u014597198/article/details/89841199