我正在寻找一种 CSS 解决方案来根据文本是否分成多行来以不同方式对齐文本。没有 Javascript,谢谢。不过,我对边缘浏览器的支持很满意。
这是我想要实现的目标:
当文本内容只占一行时,我希望它遵守text-align: center;
。否则,我希望它是 text-align: left
。
我知道我可以根据以下条件使用 Javascript 分配不同的类:
- 字符数
- 元素高度与行高
但这些解决方案并不通用,而且有很多复杂性。我正在寻找的是一个 CSS(可能是 CSS3 edge)解决方案,以解决我至今仍 Unresolved 问题。
最佳答案
这是一个纯 CSS 解决方案:
div {
background-color: yellow;
width: 200px;
}
div span {
display: inline-block;
position: relative;
left: 50%; /* move content to the right until the left side is aligned to the middle of the div container (at 100px) */
-webkit-transform: translateX(-50%); /* move half of content's width back to the left. This centers content.*/
-moz-transform: translateX(-50%);
transform: translateX(-50%);
}
<div>
<span>this is a single line content</span>
</div>
<br />
<div>
<span>this is a single line</span>
</div>
<hr />
<div>
<span>this is an example of multi line content</span>
</div>
<br />
<div>
<span>this is an example of very long multi line content that occupies three rows</span>
</div>
通过将您的内容放在 inline-block
中,您可以将此类内容的宽度限制在 div 容器内。
如果你不能在你的标记中添加一个额外的元素(span
),你仍然可以只用 div 做你想做的事,用
div {
background-color: yellow;
max-width: 200px;
display: inline-block;
position: relative;
left: 50%;
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
transform: translateX(-50%);
}
然而,黄色背景仅覆盖内容区域,而不是 200px。我试过使用伪元素 :before
无济于事。
关于css - 根据文本是否为多行以不同方式对齐文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30668401/