如何讓不定寬高的盒子居中

1、利用彈性布局,這是我認(rèn)為最簡單的且容易理解的方法

html:

<body>

<div class="one">

<div class="two">wo</div>

<div class="three">shi</div>

<div class="four">xian</div>

<div class="five">yu</div>

</div>

</body>

css:

<style>


????????.one {

width: 500px;

height: 500px;

background-color: royalblue;

display: flex; //彈性布局

justify-content: space-around; //水平居中

align-items: center; //垂直居中

}

.one>div {

background-color: yellowgreen;

}

</style>

2、利用css3和定位的方法

html:

<body>

<div class="one">

<div class="two">wo</div>

</div>

</body>

css:

<style>


????.one {

position: relative;

width: 200px;

height: 200px;

background-color: rebeccapurple;

}

.two {

position: absolute;

top: 50%;

left: 50%;

transform: translate(-50%,-50%);

}

</style>

3,利用css

html :

<body>

<div class="one">

<div class="two">wo</div>

</div>

</body>

css:

<style>


????????.one {

display: table-cell;

text-align: center;

vertical-align: middle;

width: 100px;

height: 100px;

background-color: red;

}

.two {

vertical-align: middle;?(把此元素放置在父元素的中部。)

display: inline-block;

}

</style>

注意點:一定要在子盒子里面添加內(nèi)容,因為子盒子的div本身是沒有寬高的,如果你不加內(nèi)容,根本無法實現(xiàn)效果

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容