简体   繁体   English

如何居中div但将文本左对齐?

[英]How to center a div but left align text inside?

I want to put a div block in the center of a page, but the text should stay left of the centered block. 我想在页面的中央放置一个div块,但文本应留在居中的块的左侧。

The problem is when I set the div to center and p to left, the content inside p is on the left of entire page not the left of centered block. 问题是当我将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> 

In your example, margin: auto; 在您的示例中, margin: auto; or margin: 0 auto; margin: 0 auto; is the correct approach, however div is block level element, and it occupies the entire available width by default, so the margin: auto; 是正确的方法,但是div是块级元素,默认情况下它占用整个可用宽度,因此margin: auto; has no effects visually. 视觉上没有影响。

All you need is to declare the width or max-width that is either percentage or fixed, as long as it's smaller than the parent element. 您需要声明的widthmax-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> 

Additionally, You can do it with display: table; 此外,您可以使用display: table; because it has the shrink-to-fit feature. 因为它具有缩小以适合的功能。 This works even without any width being set there. 即使没有在此处设置任何宽度也可以使用。

 .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> 

Or, display: inline-block; 或者, display: inline-block; similar feature as above. 与上述类似的功能。 Note, an additional wrapper is required if you don't want to target the body tag. 请注意,如果您不想定位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> 

By default, the text is always left. 默认情况下,文本始终保留。 And you should give width to the container or it will be of full size as of the page. 您应该给容器指定宽度,否则宽度将为页面的全尺寸。

.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>

Do you mean at the center of the page ? 您是指页面中心吗? Else you can do like this 否则你可以这样

div.container {
   text-align: center;
   max-width : 700px;
   margin : auto;
   background : blue;
   }

p {
    text-align: left;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM