如何在 div 中居中可变宽度 p 元素?
使用 . 使固定宽度的块元素居中很容易margin: 0px auto;
。但是我怎样才能设置这个 p 元素的宽度以精确地包含它的子元素,同时保持它作为block
边距工作所必需的?
HTML
<div>
<p>Center me</p>
</div>
CSS
div {
width: 300px;
}
p {
margin: 0px auto;
}
如何在 div 中居中可变宽度 p 元素?
使用 . 使固定宽度的块元素居中很容易margin: 0px auto;
。但是我怎样才能设置这个 p 元素的宽度以精确地包含它的子元素,同时保持它作为block
边距工作所必需的?
HTML
<div>
<p>Center me</p>
</div>
CSS
div {
width: 300px;
}
p {
margin: 0px auto;
}
p
是一个block
元素,当你放入另一个块元素时:
<div>
<p>Center me</p>
</div>
其中width
,将是父级的宽度(使用您的 CSS,300px
)。规则margin: 0 auto;
或更明确,设置auto
为margin-left
and margin-right
,将元素本身放在父元素的中心。
所以当parent
和child
具有相同的宽度时,它是没有意义的。
如果需要,您可以使用text-align
属性将其中的文本居中,在您的情况下,您可以将其margin
用于您的div
元素(例如,如果它的父元素是body
):
<body>
<div>
<p>Center me</p>
</div>
</body>
在 CSS 中:
div {
width: 300px;
margin: 0 auto;
}
p {
text-align: center;
}
您也可以将您的p
元素设置为inline-block
并text-align: center;
为父级制作:
body {
background: gray;
}
div {
margin: 0 auto;
width: 300px;
background: yellow;
text-align: center;
}
p {
display: inline-block;
background: pink;
}