Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to centre a block of left aligned text within a div, but I need the visual width of the text block to be centred not the block itself.

In many cases this may be the same thing, but think of a case where the div is fairly narrow (think mobile widths) and the text is too long to fit on one line, so it needs to overflow.

In the examples below, I am showing the text block as light blue to illustrate, but in practice they will be the same colour as the parent div (white). There are also no line breaks in any text used.

enter image description here

In the 1a, the text is only one line and it is smaller than the maximum width of the text block, so I can set the text block to the width of the text and there isn't a problem.

In 2a however, the text is longer than the maximum width and so wraps to the next line. The effect of this is that the visible text block doesn't appear centred any more.

How can I display both of these situations as 1b and 2b only using HTML and CSS?

Edit 1: It seems that everyone is telling me how to achieve the situation in 1a and 2a, but I already have that. I want to achieve the situation in 1b and 2b.

Edit 2: The code I'm using is essentially the same as what David gave in his link (http://jsfiddle.net/davidThomas/28aef/). The use of a colour for the text area is just to illustrate this point though. If you change that to white (http://jsfiddle.net/28aef/2/) you can see how the text block no longer looks centred (i.e. left and right margins aren't equal)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
358 views
Welcome To Ask or Share your Answers For Others

1 Answer

I know this is old, but I just had the same issue, and I agree that none of these solve it. This one may not be 100% cross-browser (haven't done testing) but it works!

Now the restriction is you have to put in the line-break yourself, but it seems that is what needs to be done regardless in this kind of situation.

http://jsfiddle.net/28aef/2/

div.textContainer {
    text-align: center;
    border: 1px solid #000;
    height: 100px;
    padding: 10px 0;
}

div.textContainer p {
    display: inline-block;
    text-align: left;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...