html - 带有长单词的 CSS 居中文本

标签 html css text alignment center

有没有一种简单的方法可以使文本水平居中,即使非常长的单词需要拉伸(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;
   }

导致“蜂鸟”偏离中心:

Off-centered "hummingbirds"

如果“蜂鸟”这个词正确居中,它会很好地放在金盒子里。

摆弄它:
https://jsfiddle.net/m6h37q2z/

添加注释 #1:
这个问题不是关于如何删除填充或减小字体大小或使框更大......这些都是非常容易的调整(并且会破坏设计)。这个问题是关于如何将“蜂鸟”这个词居中的。

添加注释#2:
对于那些说没有足够空间的人,这里有一张经过 Photoshop 处理的屏幕截图,证明有足够的空间:

enter image description here

最佳答案

我不认为可以直接做到这一点,但肯定有办法。

你可以通过使用 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;
}

如您所见,我更改了一些内容。而不是添加 20pxpadding我把父容器的宽度设为40px更大。因为<section>标签正在使用 display: flex属性(property) justified-content child <p>标签将在父级中居中 <section> (flex-direction 是默认的 row

此外,每个 <span><p> 内也居中对齐(使用 align-items 沿横轴对齐 - flex-directioncolumn

这是 fiddle :https://jsfiddle.net/o0nq9pgt/

结果如下:

enter image description here

关于html - 带有长单词的 CSS 居中文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38983465/

相关文章:

python - 使用文本文件创建 Python 登录系统

html - css 在 IE 9 中不起作用,但在 chrome 中运行良好

javascript - 按类名计数器在 javascript 中不起作用

javascript - 添加行运行时时如何在数据表中为 td 添加类?

html - 导航栏拉伸(stretch)到覆盖屏幕

css - 在 Firefox 中使用带有剪辑路径的外部 svg

linux - 在 Linux 中的文本文件中的某个短语之前添加空行?

android - Android 中的自定义 ListView,图标和文本不起作用

jquery - 在当前 div 之外复制 div

html - 让基本的物化 CSS 下拉菜单正常工作