今天總結下幾種div中的內容水平居中的幾種方法,至於好壞我還不是很清楚,就不闡述,希望有大佬能指示下,小弟不勝感激
1.首先是常規的 margin屬性,上下固定,左右自適應
<style> .div5{ width: 200px; border: 1px solid darkgoldenrod; } .div5 p{ border: 1px solid darkorange; margin: 25% auto; width: 100px; } </style> <div class="div5"> <p> this is a demo this is a demo this is a demo this is a demo </p> </div>
2.div高度自適應的情況
div在不設置高度的時候,會被里面的內容撐開,內容自動填充在div中,無論是一行內容還是多行內容,此時不需要設置垂直居中,內容自動在中間的,
想要看的更直觀些,只需要加上padding元素,內容四周便會留下空白,實現水平垂直居中的效果
<style type="text/css"> .div1{ width: 200px; border: 1px solid red; padding: 20px; } </style> <div class="div1"> this is a demo this is a demo this is a demo this is a demo </div>
3. 設置高度,多行的
當行的文字內容我們用line-height就能解決
多行的我們需要在里面加一個塊級標簽<div><p>
3.1 絕對定位,脫離文檔流的方式
<style type="text/css"> .div2{ width: 200px; height: 200px; border: 1px solid blue; position: relative; } .div2 p{ width: 150px; border: 1px solid blueviolet; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%) } </style> <div class="div2"> <p> this is a demo this is a demo this is a demo this is a demo </p> </div>
3.2 模擬表格形式
<style> .div3{ width: 200px; height: 200px; border: 1px solid green; display: table;//此元素會作為塊級表格來顯示(類似 <table>),表格前后帶有換行符。 } .div3 p{ border: 1px solid darkred; display: table-cell;//此元素會作為一個表格單元格顯示(類似 <td> 和 <th>) vertical-align: middle; text-align: center; } </style> <div class="div3"> <p> this is a demo this is a demo this is a demo this is a demo </p> </div>
4.CSS3Flex布局
<style>
.div4{
width: 200px;
height: 200px;
border: 1px solid darkgoldenrod;
display: flex;
justify-content: center;
align-items: center;
}
.div4 p{
border: 1px solid darkorange;
}
</style>
<div class="div4">
<p>
this is a demo
this is a demo
this is a demo
this is a demo
</p>
</div>
以上就是小弟常用的幾種方式,若有新的方式再跟大家分享