[英]How to center a div but left align text inside?
我想在页面的中央放置一个div块,但文本应留在居中的块的左侧。
问题是当我将div
设置为中心并将p
为左侧时, p
内的内容位于整个页面的左侧而不是居中块的左侧。
.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
是块级元素,默认情况下它占用整个可用宽度,因此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>
默认情况下,文本始终保留。 您应该给容器指定宽度,否则宽度将为页面的全尺寸。
.container {
width: 1000px;
height: 500px;
margin: auto;
border: 1px solid red;
}
<div class="container">
<div class="another-container">
<p>Some text goes here.</p>
</div>
</div>
您是指页面中心吗? 否则你可以这样
div.container {
text-align: center;
max-width : 700px;
margin : auto;
background : blue;
}
p {
text-align: left;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.