- CSS居中算是一個比較基礎的問題,在實際運用中,需要考慮到的一般是兩種情況
- 一種是主要是表現(xiàn)為文字,圖片等行內元素的居中
- 一種是指 div 等塊級標簽元素的居中
文字圖片的居中
text-align: center
<div class="center">
<span class="center_text">123</span>
</div>
.center{
text-align:center;
}
center_text{
display:inline-block;
width:500px
}
- 這種方式是在父元素中添加
text-align:center時,直接子元素如果是inline或inline-block,那么子元素在父元素中居中
margin: 0 auto
<div class="center">
<span class="center_text">
塊級元素 + 設置高度 + margin: 0 auto;
</span>
</div>
.center_text {
display: block;
width: 500px;
margin: 0 auto;
}
- 這種對齊方式要求內部元素
.content_text是塊級元素,并且不能脫離文檔流(如設置position:absolute),否則無效。
塊級標簽元素的居中
脫離文檔流的居中方式
<div class="mask">
<div class="content">我是要居中的板塊,</div>
</div>
.mask {
display: block;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #000;
z-index: 1;
}
.content {
display: block;
position: fixed;
width: 666px;
height: 400px;
top: 50%;
left: 50%;
margin-left: -333px;
margin-top: -200px;
/* transform: translate(-50%, -50%); */
z-index: 2;
background-color: #fff;
}
- 把內部div設置寬高之后,再設置top、left各為50%,設置完之后,這里是按照左端居中的,接著我們使用負邊距的方式調整,將
margin-top設置為負的高度的一半,margin-left設置為負的寬度的一半,就可以居中了。也可以用 transform: translate(-50%, -50%); 替代margin-top、margin-left,直接一步到位
使用css3計算的方式居中元素calc
<div class="mask">
<div class="content">我是要居中的板塊,</div>
</div>
.mask {
position: relative;
width: 100vw;
height: 100vh;
border: 1px solid #ccc;
}
.content {
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 150px);
width: 300px;
height: 100px;
border: 1px solid #000;
}
- 這種方式同樣是將脫離文檔流的元素,然后使用計算的方式來設置top和left;
??今天是10月1號,國慶節(jié),我起了個大早,忘記了今天不上班,剛剛去看了好聲音,真不錯,出門剪了個不漂亮的發(fā)型?? ,還吃了炸雞,然后,然后就上火長痘痘了,ε=(′ο`*)))唉,.最后祝大家國慶快樂,祝我們祖國越來越強大 ??!!!
<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="http://music.163.com/outchain/player?type=2&id=1851244378&auto=1&height=66"></iframe>
<font size="2">最后更新于 2021-10-1</font>