南通颐猩文化传播有限公司

當前位置:首頁 >  IDC >  服務(wù)器 >  正文

CSS實現(xiàn)子元素div水平垂直居中的示例

 2020-10-19 16:15  來源: 腳本之家   我來投稿 撤稿糾錯

  域名預(yù)訂/競價,好“米”不錯過

這篇文章主要介紹了CSS實現(xiàn)子元素div水平垂直居中的示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

div基本布局

<div class="main">
<div class="center"></div>
</div>

css樣式

1. 配合定位與margin:auto

父元素加相對定位,子元素加絕對定位

.main{
width: 300px;
height: 300px;
background-color: red;
position: relative;
}
.center{
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}

2.利用flex布局,設(shè)置水平與豎直方向的內(nèi)容居中。

.main{
width: 300px;
height: 300px;
background-color: red;
display: flex;
justify-content: center;
align-items: center;
}
.center{
width: 100px;
height: 100px;
background-color: greenyellow;
}

3.利用position:absolute與transform

:這里需要記住的是transform中translate使用百分比時相對的是自己的長寬,不是父盒子的。

.main{
width: 300px;
height: 300px;
background-color: red;
position: relative;
}
.center{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
}

4.定位 與負margin配合

只適合子盒子長寬固定的情況

.main{
width: 300px;
height: 300px;
background-color: red;
position: relative;
}
.center{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}

5.display:table-cell

display:table-cell;與vertical-align:middle 的作用是讓子盒子在數(shù)值方向上居中

margin:auto;則讓子盒子在水平方向居中,若只想讓盒子在某個方向居中,去掉另一個就可以了。

.main{
width: 300px;
height: 300px;
background-color: red;
display: table-cell;
vertical-align: middle;
}
.center{
width: 100px;
height: 100px;
background-color: #000;
margin: auto;
}

文章來源:腳本之家,原文鏈接:https://www.jb51.net/css/743597.html

申請創(chuàng)業(yè)報道,分享創(chuàng)業(yè)好點子。點擊此處,共同探討創(chuàng)業(yè)新機遇!

相關(guān)文章

熱門排行

信息推薦