容器外的文本中心

问题描述 投票:0回答:2

是否可以将文本置于css中心并使其从左向右扩展而不使用javascript并且不知道它有多大?

在我的尝试中,文本总是向右扩展。

.container {
  width: 90px;

  border: 1px solid red;
  
  text-align: center;
  white-space: nowrap;
  overflow: visible;
}
  <div class="container">Hello very long text</div>
  <div class="container">Small text</div>
html css css3
2个回答
2
投票

您可以使用Flexbox执行此操作:

.container {
  display: flex; /* displays flex-items (children) inline */
  justify-content: center; /* centers them horizontally */
  width: 90px;
  border: 1px solid red;
  /*text-align: center;*/
  white-space: nowrap;
  overflow: visible;
}
<div class="container">Hello very long text</div>
<div class="container">Small text</div>

3
投票

您可以做的是下面的解决方案:制作容器position: relative,将aspan放入其中并将下面的设置应用于该范围以使其居中(位置:绝对等)您必须给容器一些高度才能使虽然工作。

.container {
  width: 90px;
  border: 1px solid red;
  white-space: nowrap;
  overflow: visible;
  text-align: center;
  position: relative;
  height: 1.4em;
}

.container>span {
  display: block;
  position: absolute;
  left: 50%;
  transform: translateX(-50%)
}
<div class="container"><span>Hello very very very long text</span></div>
<div class="container">Small text</div>
© www.soinside.com 2019 - 2024. All rights reserved.