居中對齊
阿新 • • 發佈:2021-02-15
整理一下CSS元素居中對齊的方式,看看自己到底有多少貨。
文章目錄
下面是要居中對齊的元素,程式碼如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>元素居中</title>
</head>
<body>
<div class="main" >
<div></div>
</div>
</body>
</html>
flex
flex佈局設定的是內部元素的位置,而不是自己本身的位置。
.main {
width: 200px;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
background: tomato;
}
.main div{
width: 80px;
height: 80px;
background: turquoise;
}
position+margin
目標元素的Position屬性必須是absolute,而其父元素的position是relative,(只要不是static即可)通過left,top,right,bottom的距離都是零,然後外邊距自動對齊就OK了。目標元素必須有準確的width和height值。
.main {
width: 200px;
height: 200px;
position: relative;
background: tomato;
}
.main div{
width : 80px;
height: 80px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
background: turquoise;
}
transform+position
目標元素的position屬性是absolute,父元素的position屬性為relative,相對於父元素距上方和左側各50%,然後再向上和左移動自身的50%。
.main {
width: 200px;
height: 200px;
position: relative;
background: tomato;
}
.main div{
width: 80px;
height: 80px;
position: absolute;
left: 50%;
top: 50%;
right: 0;
transform: translate(-50%,-50%);
background: turquoise;
}
所有的方式只有如下這一種結果
文字的居中對齊也是挺常用的,這裡也說一個簡單的吧。
文字居中對齊
text-align為center時,文字水平居中;line-heigth和heigth等值時,文字垂直居中。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>元素居中</title>
<style>
.main {
width: 200px;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
background: tomato;
}
.main p{
width: 80px;
height: 80px;
background: chartreuse;
text-align: center;
line-height: 80px;
}
</style>
</head>
<body>
<div class="main">
<p>居中文字</p>
</div>
</body>
</html>