简体   繁体   中英

How to left-align centered text only if hits a line break?

How can I condition my text to become left-aligned if hits the end of its contained space and has to switch to the next line? Is there something inherent within CSS that can detect it, or does it have to be a JavaScript solution?

Here's the fiddle so you can see how it should behave: https://jsfiddle.net/fj4ddmey/2/

 .text.container { margin: 0 auto; text-align: center; width: 350px; border: 1px solid black; } .text.container.two { text-align: left; } 
 <div class="text container"> <p>This is how short sentences should look</p> </div> <div class="text container"> <p>This text should be left aligned because it hits a line break</p> </div> <div class="text container two"> <p>This is how it should look, but it needs to be a fluid solution</p> </div> 

Use flexbox like that

 .container { display: flex; justify-content: center; } 
 <div class="container"> <p>This is how it should look, but it needs to be a fluid solution</p> </div> 

Here is JSFiddle demo

You can set the <p> as inline block, so that text-align:center on the container will center the <p> tag first, rather than the text. And inline-block has the shrink-to-fit feature, means the width is determined by the content, and never goes beyond the container, with text-align:left , text inside will be left aligned when it wraps.

 .container { width: 350px; margin: 0 auto; text-align: center; outline: 1px solid black; } .container p { display: inline-block; text-align: left; outline: 1px dotted red; } 
 <div class="container"> <p>This is how short sentences should look</p> </div> <div class="container"> <p>This text should be left aligned because it hits a line break</p> </div> 

You can use jQuery to determine the element height, and if its greater than one line, add a class to justify the text appropriately.

Something like this should work:

function countLines(e) {
  var elementHeight = e.innerHeight();
  var lineHeight = parseInt(e.css('line-height'));
  var lines = elementHeight / lineHeight;
  return(lines > 1);
}

$('p').each(function() {
    if(countLines($(this))) {
        $(this).addClass('two'); //class to left justify
    }
})

You can see it working here: https://jsfiddle.net/igor_9000/fj4ddmey/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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