国产成人精品无码青草_亚洲国产美女精品久久久久∴_欧美人与鲁交大毛片免费_国产果冻豆传媒麻婆精东

15158846557 在線咨詢 在線咨詢
15158846557 在線咨詢
所在位置: 首頁 > 營銷資訊 > 網(wǎng)站運營 > CSS實現(xiàn)子元素div水平垂直居中的示例

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

時間:2024-02-24 00:00:01 | 來源:網(wǎng)站運營

時間:2024-02-24 00:00:01 來源:網(wǎng)站運營

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

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

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布局,設置水平與豎直方向的內(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

關鍵詞:垂直,居中,示例,水平,實現(xiàn)

74
73
25
news

版權所有? 億企邦 1997-2025 保留一切法律許可權利。

為了最佳展示效果,本站不支持IE9及以下版本的瀏覽器,建議您使用谷歌Chrome瀏覽器。 點擊下載Chrome瀏覽器
關閉