如果点击其包含空间的末尾并且必须切换到下一行,我如何调整文本以使其左对齐? CSS中是否存在可以检测它的东西,还是必须是JavaScript解决方案?
这是小提琴,所以你可以看到它应该如何表现: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>
&#13;
答案 0 :(得分:3)
像这样使用flexbox
.container {
display: flex;
justify-content: center;
}
&#13;
<div class="container">
<p>This is how it should look, but it needs to be a fluid solution</p>
</div>
&#13;
答案 1 :(得分:2)
您可以将<p>
设置为内嵌块,以便容器上的text-align:center
将<p>
标记放在首位,而不是文本。并且内联块具有缩小到适合的特征,意味着宽度由内容决定,并且永远不会超出容器,使用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;
}
&#13;
<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>
&#13;
答案 2 :(得分:1)
您可以使用jQuery来确定元素高度,如果它大于一行,则添加一个类来正确地对齐文本。
这样的事情应该有效:
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
}
})