[英]how can i have multiple lines of text centered if they are not wide enough, and justified if they fill the entire width?
I have a large paragraph that I want to keep in one p tag. 我有一个很大的段落要保留在一个p标签中。 I have seen some solution, but it requires every line to be in a different tag.
我已经看到了一些解决方案,但是它要求每一行都在不同的标签中。
the idea is to have lines justified and centered at the same time. 想法是使线条同时对齐并居中。 I know in CSS it does not make sense as the property text-align defines both for some strange reason.
我知道在CSS中这是没有意义的,因为text-align属性出于某种奇怪的原因而定义了两者。
before posting a solution, please create one <p>
or <div>
or whatever you want, fill it with three lines of text, and make sure that the first two are justified, and the last one is centered. 在发布解决方案之前,请创建一个
<p>
或<div>
或任何您想要的内容,用三行文本填充它,并确保前两行对齐,最后一行居中。 That is exactly what I am asking for. 这正是我要的。
I understood your original question and the clarification to be asking for two different things. 我理解您最初提出的问题以及要求提供两种不同内容的说明。
If you're trying to make a page that displays short text centered and a long paragraph justified then you could use javascript to check the length of the text and apply the appropriate style. 如果您要使页面显示的短文本居中且长段落对齐,则可以使用javascript检查文本的长度并应用适当的样式。
It would be pretty straightforward to do something like this with jquery: 用jquery做这样的事情很简单:
<p id='fixed_text'>
Text above a certain length can be displayed as justified and shorter text can be centered
</p>
...
var maxLength = 100;
function sizeParagraph(){
if($('#fixed_text').text().length > maxLength){
$('#fixed_text').css('text-align','justified');
} else {
$('#fixed_text').css('text-align','center');
}
}
Rationale: if the height() is equal to the line-height, the paragraph (or any block element) gains the class "oneliner" (which is centered with a css rule). 基本原理:如果height()等于line-height,则该段落(或任何块元素)将获得“ oneliner”类(以css规则为中心)。
css: CSS:
/*
all Ps should be {
text-align: justified;
height: auto;
} by default
*/
.oneliner {text-align: center}
js: js:
$(document).ready(function(){
$('p').each(function(){ // change the "p" selector at will
var $this = $(this);
if(Math.round(parseFloat($this.css('lineHeight'), 10)) == $this.height())
$this.addClass('oneliner');
});
});
Note that this will not work if you have nested images or block elements taller than the paragraph's line-height, or if the height is not auto. 请注意,如果嵌套的图像或块元素的高度大于段落的行高,或者高度不是自动的,则此方法将无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.