常用的css將元素垂直居中的方法
1. 使用line-height將單行文本垂直居中
設置line-height等於height,可使單行文本垂直居中
例:
div {
height: 50px;
width: 200px;
border: 1px solid #ccc;
}
效果如下:
加入line-height屬性後
div {
height: 50px;
width: 200px;
border: 1px solid #ccc;
line-height: 50px;
}
效果
2.用定位的方法實現垂直居中
使用position: absolute;和position: relative;利用定位的“子絕父相”來使子元素相對於父元素垂直居中。原理是使子元素先向下移動父元素的50%,再向上移動自己大小的50%。
例:
.father {
height: 100px;
width: 100px;
border: 1px solid #ccc;
margin: 100px auto;
}
.son {
height: 30px;
width: 30px;
background-color: pink;
}
效果如下:
加入position: absolute;和position: relative;屬性後
.father {
position: relative;
height: 100px;
width: 100px;
border: 1px solid #ccc;
margin: 100px auto;
}
.son {
position: absolute;
top: 50%;
transform: translateY(-50%);
height: 30px;
width: 30px;
background-color: pink;
}
效果
3.利用flex佈局實現垂直居中
原理是通過設置flex的主軸方向和在主軸方向還是副軸方向上居中的方法來實現(flex默認的主軸方向是row)
.father {
height: 100px;
width: 100px;
border: 1px solid #ccc;
margin: 100px auto;
}
.son {
height: 30px;
width: 30px;
background-color: chartreuse;
}
方法1:給父元素設置display: flex;和align-items: center; 主軸默認橫向,副軸豎向,使子元素在副軸方向上居中。
.father {
display: flex;
align-items: center;
height: 100px;
width: 100px;
border: 1px solid #ccc;
margin: 100px auto;
}
.son {
height: 30px;
width: 30px;
background-color: chartreuse;
}
方法2:給父元素設置display: flex;和 flex-direction: column;主軸設置爲豎向,副軸橫向,justify-content: center;使子元素在主軸方向上居中。
.father {
display: flex;
flex-direction: column;
justify-content: center;
height: 100px;
width: 100px;
border: 1px solid #ccc;
margin: 100px auto;
}
.son {
height: 30px;
width: 30px;
background-color: chartreuse;
}
方法3:給子元素設置align-self: center;屬性,使子元素在副軸方向上居中。
.father {
display: flex;
height: 100px;
width: 100px;
border: 1px solid #ccc;
margin: 100px auto;
}
.son {
align-self: center;
height: 30px;
width: 30px;
background-color: chartreuse;
}
三種方法得到的效果均爲:
4.利用絕對定位+margin: auto;
“子絕父相”後,給子元素設置margin: auto;bottom: 0;top: 0;即可實現垂直居中。
.father {
height: 100px;
width: 100px;
border: 1px solid #ccc;
margin: 100px auto;
}
.son {
height: 30px;
width: 30px;
background-color: pink;
}
加入屬性後:
.father {
position: relative;
height: 100px;
width: 100px;
border: 1px solid #ccc;
margin: 100px auto;
}
.son {
position: absolute;
margin: auto;
bottom: 0;
top: 0;
height: 30px;
width: 30px;
background-color: pink;
}
效果:
5.利用vertical-align: middle;使文字相對於圖片垂直居中
.father {
height: 68px;
width: 300px;
border: 1px solid #ccc;
margin: 100px auto;
}
通過給圖片設置vertical-align: middle;屬性:
.father {
height: 68px;
width: 300px;
border: 1px solid #ccc;
margin: 100px auto;
}
img {
vertical-align: middle;
}
效果:
這種方法涉及到文字的底線,基線,中線和頂線的知識,不懂的小夥伴可以先去了解一下。
6.通過添加僞元素的方法使內容達到垂直居中
此方法的原理和第五條的原理類似,就是通過設置一個僞元素達到方法5中圖片的作用,但是利用僞元素不會佔取空間。
.father {
height: 50px;
width: 200px;
border: 1px solid #ccc;
margin: 100px auto;
}
添加僞元素後:
.father {
height: 50px;
width: 200px;
border: 1px solid #ccc;
margin: 100px auto;
}
.father::after {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
總結
以上就是本次介紹的6種常用的使內容垂直的居中的方法,大家可以根據實際遇到的情況靈活使用。