[英]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?
CSS中是否有固有的东西可以检测到它,或者它必须是JavaScript解决方案?
Here's the fiddle so you can see how it should behave: https://jsfiddle.net/fj4ddmey/2/ 这是小提琴,因此您可以看到它的行为: 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 像这样使用
flexbox
.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 这是JSFiddle演示
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. 您可以将
<p>
设置为内联块,这样容器上的text-align:center
将首先使<p>
标记居中,而不是文本居中。 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. 内联块具有缩小以适合的功能,这意味着宽度由内容决定,并且永远不会超出容器范围,使用
text-align:left
,包装时,其中的文本将保持左对齐。
.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. 您可以使用jQuery确定元素的高度,如果元素的高度大于一行,则添加一个类以适当地证明文本正确。
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/ 您可以在这里看到它的工作: https : //jsfiddle.net/igor_9000/fj4ddmey/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.