Center a short text block that is align left

匆匆过客 提交于 2020-01-23 11:19:29

问题


It is easy to center a long text with margin 0 auto and control the distance with the margin or the padding.

But, Is it possible to center a text without knowing the width and if that text is align left ?

  • Center a short text
  • text alignt left
  • I don't know the width

Here is the example to check: http://jsfiddle.net/j4Y3k/5/

CSS:

#long {
    margin:50px auto;
    text-align:left;
    padding: 0px 100px;
    background:white;
}

#short {
    margin:0px auto;
    text-align:left;
}

HTML:

<div id="long">
long, long,long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, 
</div>

<div id="short"> 
short, short, short<br>
short, short, short, short, short, short<br>
short, short
</div>

回答1:


You can do it easily if you allow yourself to do the following:

<div class="wrap">
    <div id="short">short, short, short
        <br>short, short, short, short, short, short
        <br>short, short</div>
</div>

and apply the following CSS:

.wrap {
    text-align: center;
}
#short {
    margin:0px;
    auto;
    text-align:left;
    outline: 1px dotted blue;
    display: inline-block;
}

See fiddle: http://jsfiddle.net/audetwebdesign/GywRR/

The inline-block will shrink-to-wrap your content and still respond to the text-align: center property declared for the parent container.

Why inline-block versus block

block's will use the maximum available width, usually the width of the parent container. inline-block will shrink-to-fit (the term in the w3.org docs!), which usually gives you a width less than that of the parent container, which then allows the centering to work.




回答2:


You need to set a width when centering using "margin auto". Also you had a syntax error in your margin property;

#short {
    margin:50px auto;
    text-align:left;
    width:300px;
}

http://jsfiddle.net/j4Y3k/2/

You may think you've centered the long element, but this is just because its ran out of space, and the 100px padding has forced the gaps on either side. You need to set width property on this too if you wish to truely center it.



来源:https://stackoverflow.com/questions/16189696/center-a-short-text-block-that-is-align-left

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!