简体   繁体   English

如何在div的中心向左对齐文本?

[英]How do I have left-aligned text in the center of a div?

I was wondering if anybody knows how to center text that is left aligned. 我想知道是否有人知道如何居中对齐文本。 Here's an example of what I mean: 这是我的意思的示例:

This text
is
left aligned.

                                  This text
                                  is
                                  left aligned
                                  and in
                                  the center (isn).

How can I do that inside a div? 如何在div内执行此操作? I've tried the one answer I've seen everywhere which is to put text-align:center in a parent div and then in the child div put text-align: left, but this does not seem to work. 我已经尝试了一个我在所有地方都看到的答案,即将text-align:center放在父div中,然后在子div中将text-align:left放进去,但这似乎行不通。 Here is an example: http://codepen.io/nrojina0/pen/OXGdXJ 这是一个示例: http : //codepen.io/nrojina0/pen/OXGdXJ

 div#stores { font-size: 1.25em; width: 100%; text-align: center; border: 1px solid black; } div#storesleft { display: inline-block; float: left; width: 33%; text-align: left; margin: 0 auto; border: 1px solid black; } 
 <div id="stores"> <div id="storesleft"> Boo and Roo's <br>112 E. Moore St. <br>Southport, NC 28461 <br>(910)363-4275 <br> </div> </div> 

I was wondering if anybody knows how to center text that is left aligned. 我想知道是否有人知道如何居中对齐文本。

Just remove the float from the "centered" child.. 只需从“居中”子项中删除float

"The first rule of centering is...don't use float!" “居中的第一个规则是……不要使用浮点数!”

 div#stores { font-size: 1.25em; width: 100%; text-align: center; padding: 1em; } div#storesleft { display: inline-block; width: 33%; text-align: left; margin: 0 auto; } 
 <div id="stores"> <div id="storesleft"> Boo and Roo's <br>112 E. Moore St. <br>Southport, NC 28461 <br>(910)363-4275 <br> </div> </div> 

I want the text in each of the three child divs to be left aligned, but still in the center of their div. 我希望三个子div中的每个文本保持左对齐,但仍位于其div的中心。 How would I do that? 我该怎么做?

From your amended requirements (in the comments) I'd use flexbox to avoid have to add additional wrappers. 根据您的修订要求(在注释中),我将使用flexbox以避免必须添加其他包装。

Demo with required additional wrappers : Codepen Demo 带有附加包装的演示Codepen演示

Flexbox Demo: Flexbox演示:

 div#stores { font-size: .85em; width: 100%; display: flex; justify-content: space-around; } div#storesleft { border: 1px solid black; } div#storescenter { border: 1px solid black; } div#storesright { border: 1px solid black; } 
 <div id="stores"> <div id="storesleft"> Boo and Roo's <br>112 E. Moore St. <br>Southport, NC 28461 <br>(910)363-4275 <br> </div> <div id="storescenter"> Natural Food Store <br>1920 US Hwy 70 SW <br>Hickory, NC 28602 <br>(828)322-5316 <br> </div> <div id="storesright"> Routh's Grocery <br>3796 Chatham Street <br>Bennett, NC 27208 <br>(336)581-3465 <br> </div> </div> 

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

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