有没有一种简单的方法可以使文本水平居中,即使非常长的单词需要拉伸(stretch)到周围的填充物中也能正常工作?
例如,以下内容:
HTML
<section>
<p>
Some animals in the wild, like
hummingbirds, have long names.
</p>
</section>
CSS
section p {
width: 75px;
text-align: center;
background: gold;
padding: 20px;
}
导致“蜂鸟”偏离中心:
如果“蜂鸟”这个词正确居中,它会很好地放在金盒子里。
摆弄它:
https://jsfiddle.net/m6h37q2z/
添加注释 #1:
这个问题不是关于如何删除填充或减小字体大小或使框更大......这些都是非常容易的调整(并且会破坏设计)。这个问题是关于如何将“蜂鸟”这个词居中的。
添加注释#2:
对于那些说没有足够空间的人,这里有一张经过 Photoshop 处理的屏幕截图,证明有足够的空间:
最佳答案
我不认为可以直接做到这一点,但肯定有办法。
你可以通过使用 flexbox 并用一些 <span>
包裹你的文本的某些部分来实现这一点。像这样的标签:
<section>
<p>
<span>Some animals in the wild, like</span>
<span>hummingbirds,</span>
<span>have long names.</span>
</p>
</section>
然后你可以像这样添加你的样式:
body {
font-family: sans-serif;
}
section {
width: 115px;
background: gold;
display: flex;
justify-content: center;
}
section p {
width: 75px;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
}
如您所见,我更改了一些内容。而不是添加 20px
的 padding
我把父容器的宽度设为40px
更大。因为<section>
标签正在使用 display: flex
属性(property) justified-content
child <p>
标签将在父级中居中 <section>
(flex-direction
是默认的 row
。
此外,每个 <span>
在 <p>
内也居中对齐(使用 align-items
沿横轴对齐 - flex-direction
是 column
。
这是 fiddle :https://jsfiddle.net/o0nq9pgt/
结果如下:
关于html - 带有长单词的 CSS 居中文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38983465/