我想在页面中央放置一个 div block ,但文本应位于居中 block 的左侧。
问题是当我将 div
设置为居中并将 p
设置为左侧时,p
中的内容位于整个页面的左侧不是居中 block 的左侧。
.container {
text-align: center;
margin: auto;
}
.container p {
text-align: left;
}
<div class="container">
<p>The quick brown fox jumps over the lazy dog.</p>
</div>
最佳答案
在您的示例中,margin: auto;
或 margin: 0 auto;
是正确的方法,但是 div
是 block 级元素,默认情况下它会占据整个可用宽度,因此 margin: auto;
在视觉上没有任何效果。
您只需声明 width
或 max-width
即可,它可以是百分比或固定值,只要它小于父元素即可。
.container {
margin: 0 auto;
max-width: 200px;
border: 1px solid;
}
<div class="container">
<p>The quick brown fox jumps over the lazy dog.</p>
</div>
此外,您可以使用 display: table;
来实现,因为它具有收缩以适合 功能。即使没有在那里设置任何宽度,这也能工作。
.container {
display: table;
margin: 0 auto;
border: 1px solid;
}
<div class="container">
<p>The quick brown fox jumps over the lazy dog.</p>
</div>
<div class="container" style="max-width: 500px;">
<h2>Example: max-width and wrapping text</h2>
<p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
</div>
或者,display: inline-block;
与上面类似的功能。请注意,如果您不想以 body
标记为目标,则需要额外的包装器。
.outer {
text-align: center;
}
.container {
border: 1px solid;
display: inline-block;
text-align: left;
}
<div class="outer">
<div class="container">
<p>The quick brown fox jumps over the lazy dog.</p>
</div>
</div>
关于html - 如何使 div 居中但在内部左对齐文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49075981/