如何将此 <div> 元素中的文本居中?
how to center text inside this <div> element?
这是 div 中的 h3(我知道使用内联样式很糟糕)。
<div style="background-color: rgb(238, 238, 238); width: 500px; height: 36pt; text-align: center;">
<h3 style="font-family: Helvetica;">Hello World!</h3></div>
如何将 h3 标签置于 div 中?
您可以在 h3 标签中添加 line-height: 36pt。
<div style="background-color: rgb(238, 238, 238); width: 500px; height: 36pt; text-align: center;">
<h3 style="font-family: Helvetica; line-height: 36pt">Hello World!</h3></div>
为了便于垂直居中,您可以将 H3
line-height
设置为与容器的高度相同(如果已知)。
在这种情况下,我们会这样做(因为您已将其设置为 36pt),即:line-height: 36pt
行高示例:
<div style="background-color: rgb(238, 238, 238); width: 500px; height: 36pt; text-align: center;">
<h3 style="font-family: Helvetica;line-height: 36pt">Hello World!</h3>
</div>
如果容器的高度是动态的且未知,则需要使用另一种形式的垂直居中,例如使用 display: table 或 显示:弹性
有关 CSS 中内容居中的资源对于找到最佳解决方案非常有用:https://css-tricks.com/centering-in-the-unknown/
您可以添加 line-height
这取决于您 <div>
的高度
<div style="background-color: rgb(238, 238, 238); width: 500px; height: 36pt; text-align: center;">
<h3 style="font-family: Helvetica; line-height: 36pt">Hello World!</h3>
</div>
看看这个example fiddle
这是 div 中的 h3(我知道使用内联样式很糟糕)。
<div style="background-color: rgb(238, 238, 238); width: 500px; height: 36pt; text-align: center;">
<h3 style="font-family: Helvetica;">Hello World!</h3></div>
如何将 h3 标签置于 div 中?
您可以在 h3 标签中添加 line-height: 36pt。
<div style="background-color: rgb(238, 238, 238); width: 500px; height: 36pt; text-align: center;">
<h3 style="font-family: Helvetica; line-height: 36pt">Hello World!</h3></div>
为了便于垂直居中,您可以将 H3
line-height
设置为与容器的高度相同(如果已知)。
在这种情况下,我们会这样做(因为您已将其设置为 36pt),即:line-height: 36pt
行高示例:
<div style="background-color: rgb(238, 238, 238); width: 500px; height: 36pt; text-align: center;">
<h3 style="font-family: Helvetica;line-height: 36pt">Hello World!</h3>
</div>
如果容器的高度是动态的且未知,则需要使用另一种形式的垂直居中,例如使用 display: table 或 显示:弹性
有关 CSS 中内容居中的资源对于找到最佳解决方案非常有用:https://css-tricks.com/centering-in-the-unknown/
您可以添加 line-height
这取决于您 <div>
<div style="background-color: rgb(238, 238, 238); width: 500px; height: 36pt; text-align: center;">
<h3 style="font-family: Helvetica; line-height: 36pt">Hello World!</h3>
</div>
看看这个example fiddle