html - 在可调整大小的 div 中居中环绕文本

标签 html css

我的网站上有一个可调整大小的侧边栏菜单。侧边栏在折叠时有一个折叠动画过渡。此侧边栏中的某些文本需要居中。问题是,如果您使用 text-align: center; 之类的东西来格式化文本,当您调整其容器 div 大小时文本会移动,因为 div 的中心点正在改变。

为了解决这个问题,我能做的最好的事情就是设置 white-space: nowrap; 并观察左侧填充以手动将文本居中。这很好用,除了我有动态生成的文本,我必须居中。这意味着使用这种方法我必须动态地找到文本的长度并相应地调整填充,这似乎是错误的。

它不必使用 nowrap 样式,但是有什么方法可以使文本在 div 中居中并且在调整 div 大小时不移动?

jsfiddle 插图:https://jsfiddle.net/singerbradley/dvmauj3f/28/#&togetherjs=nvnJwReUA7

编辑:

让我澄清一下我要做什么。我希望调整大小的 div 中的文本在 div 处于全宽时居中,并在调整 div 大小时保持在该位置。我还希望文本在容器收缩时被截断(通过使用 overflow: hidden;white-space: nowrap; 实现)而不是转到下一个线。基本上,我想要底部框中发生的事情,而当容器收缩时文本不会移动。

.enhance {
  border-color: red;
  border-style: solid;
  margin-top: 10px;
  margin-bottom: 10px;
  padding: 20px 0;
  width: 300px;
  overflow: hidden;
  transition: all .5s linear;
}

#wrap {
  text-align: center;
}

#nowrap {
  white-space: nowrap;
  text-align: center;
}

#wrap:hover {
  width: 50px;
}

#nowrap:hover {
  width: 50px;
}
<p style="width:500px;">
Hover over each box to see it in motion. The centered, line wrap text shifts with div resize.
</p>
<div id="wrap" class="enhance">This text has line wraps.</div>
<div id="nowrap" class="enhance">This text has no line wraps.</div>

最佳答案

根据您的编辑,完成此操作的方法是创建一个内部容器并将其设置为父容器的宽度。查看 <span>里面#nowrap以及为跨度添加的 CSS。

.enhance {
  border-color: red;
  border-style: solid;
  margin-top: 10px;
  margin-bottom: 10px;
  padding: 20px 0;
  width: 300px;
  overflow: hidden;
  transition: all .5s linear;
}

#wrap {
  text-align: center;
}

#nowrap {
  white-space: nowrap;
  text-align: center;
}

#nowrap span {
  display: block;
  width: 300px;
}

#wrap:hover {
  width: 50px;
}

#nowrap:hover {
  width: 50px;
}
<p style="width:500px;">
Hover over each box to see it in motion. The centered, line wrap text shifts with div resize.
</p>
<div id="wrap" class="enhance">This text has line wraps.</div>
<div id="nowrap" class="enhance"><span>This text has no line wraps.</span></div>

关于html - 在可调整大小的 div 中居中环绕文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49502754/

相关文章:

html - 组织一个带有 Visual Studio 扩展名的巨大 .css 文件?

html - 并排放置 ul li 内容

javascript - 在表单提交时调用 Javascript 函数

javascript - 如何更改脚本的字体大小?

html - UL不停留在一条线上

javascript - 带有脚本标签的外部 Javascript 文件

jquery - 多个下拉切换

css - 如何在不在 css 中重复图像的情况下添加大内容时拉伸(stretch)背景图像

javascript - 当 true 时, Angular ngif 自动发送表单

javascript - 图像损坏时隐藏 li