Centering if one line, but not centering if several lines

Is it possible to horizontally center the text if it is placed on one line, but does not perform center alignment and makes white-space: normal if it occupies several lines (preferably, but not necessarily, without javascript)?

+4
source share
2 answers

Here is the HTML + CSS solution.

Tricks:

  • <span> inside <p> has a display: inline-box; property display: inline-box; , therefore, it will be reduced to the size of its contents.

  • <p> has text-align: center , so the <span> will be centered if the size of the <span> less than the width of the <p> .

  • <span> has text-align: left , so the text will actually be left aligned.

 <!DOCTYPE html> <html> <head> <title>Center</title> <style type="text/css"> .big-box { text-align: center; width: 40em; border: 1px solid red; } .center-if-single-line { text-align: left; display: inline-block; border: 1px solid blue; } </style> </head> <body> <div> <h1>Small</h1> <p class="big-box"> <span class="center-if-single-line"> All your line are belong to us! </span> </p> <h1>Big</h1> <p class="big-box"> <span class="center-if-single-line"> All your line are belong to us! All your line are belong to us! All your line are belong to us! All your line are belong to us! All your line are belong to us! All your line are belong to us! All your line are belong to us! All your line are belong to us! All your line are belong to us! All your line are belong to us! All your line are belong to us! All your line are belong to us! All your line are belong to us! All your line are belong to us! All your line are belong to us! </span> </p> </div> </body> </html> 
+3
source

A Javascript solution - not necessarily the best - would have to find out about div / p height and make a determination from there. You need to know the height that the DOM element takes if there is only one row. If the height exceeds this value, you do one; if not, you are doing something else. You would set your default CSS to a more common phenomenon and only change it in fewer cases.

For instance:

 var tag = document.getElementById("id_here"); if(tag.offsetHeight > 18){ tag.style.textAlign = "left"; tag.style.whiteSpace = "normal";} 

You can also use jQuery. Note that offsetHeight includes an add-on.

But you really don't need a Javascript solution. I can’t think how you will do it in CSS, mind you, because it is related to the dynamic style. I would strongly suggest that this is not possible.

+1
source

Source: https://habr.com/ru/post/1402048/


All Articles