[英]How to center a <p> element inside a <div> container?
我希望我的<p>
元素位於容器<div>
的中心,就像完全居中一樣——頂部、底部、左側和右側的邊距均等地分割空間。
我怎樣才能做到這一點?
div { width: 300px; height: 100px; } p { position: absolute; top: auto; }
<div> <p>I want this paragraph to be at the center, but it's not.</p> </div>
你不需要絕對定位使用
p {
text-align: center;
line-height: 100px;
}
並隨意調整...
如果文本超過寬度並且超過一行
在這種情況下,您可以做的調整是在您的規則中包含 display 屬性,如下所示;
(我添加了背景以便更好地查看示例)
div
{
width:300px;
height:100px;
display: table;
background:#ccddcc;
}
p {
text-align:center;
vertical-align: middle;
display: table-cell;
}
在這個JBin玩它
要獲得左/右居中,然后將text-align: center
應用於div
並將margin: auto
應用於p
。
對於垂直定位,您應該確保了解這樣做的不同方式,這是一個常見問題: div 中元素的垂直對齊
♣你應該做這些步驟:
♣♣這里是這 5 個步驟的總結:
.mother_Element {
position : relative;
height : 20%;
width : 5%;
text-align : center
}
.child_Element {
height : 1.2 em;
width : 5%;
margin : auto;
position : absolute;
top:0;
bottom:0;
left:0;
right:0;
}
我就是這樣做的:
.container { display: flex; justify-content: center; align-items: center; width: 300px; height: 100px; background-color: lightgreen; }.paragraph { width: 250px; background-color: lightyellow; }
<div class="container"> <p class="paragraph">I want this paragraph to be at the center, but it's not.</p> </div>
你可以添加text-align: center;
如果您希望文本 alignment 居中,則添加到該段落
中心內容和中間內容 ?
這樣做:
<table style="width:100%">
<tr>
<td valign="middle" align="center">Table once ruled centering</td>
</tr>
</table>
哈,讓我猜猜.. 你想要 DIV ..
只需讓您的第一個外部 DIV 表現得像一個表格單元格,然后使用垂直 align:middle 對其進行樣式設置;
<div>
<p>I want this paragraph to be at the center, but I can't.</p>
</div>
div {
width:500px;
height:100px;
background-color:aqua;
text-align:center;
/* there it is */
display:table-cell;
vertical-align:middle;
}
在 p 元素上,添加 3 個樣式規則。
.myCenteredPElement{
margin-left: auto;
margin-right: auto;
text-align: center;
}
此解決方案適用於所有主要瀏覽器,IE 除外。 所以記住這一點。
在這個例子中,我基本上對 UI 元素使用了定位、水平和垂直變換來使其居中。
.container { /* set the the position to relative */ position: relative; width: 30rem; height: 20rem; background-color: #2196F3; } .paragh { /* set the the position to absolute */ position: absolute; /* set the the position of the helper container into the middle of its space */ top: 50%; left: 50%; font-size: 30px; /* make sure padding and margin do not disturb the calculation of the center point */ padding: 0; margin: 0; /* using centers for the transform */ transform-origin: center center; /* calling calc() function for the calculation to move left and up the element from the center point */ transform: translateX(calc((100% / 2) * (-1))) translateY(calc((100% / 2) * (-1))); }
<div class="container"> <p class="paragh">Text</p> </div>
我希望這會有所幫助。
你只需要添加text-align: center
到你的<div>
在您的情況下,還刪除您添加到<p>
兩種樣式。
在這里查看演示: http : //jsfiddle.net/76uGE/3/
祝你好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.