如何水平对齐溢出的文本?

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

我有一些文本可能会使父容器溢出:

body {
  margin: 200px;
}

.container {
  width: 100px;
  height: 50px;
  background-color: #bbb;
  text-align: center;
}

.header {
  white-space: nowrap;
}
<div class="container">
  <div class="header">
    Short Text
  </div>
  <div class="header">
    Very long text that should not wrap and be center aligned
  </div>
</div>

文本短时,如预期那样居中对齐。

但是,当文本溢出容器时,它不再居中对齐。

无论文本的长度如何,如何水平对齐文本?

期望的结果:

enter image description here

html css alignment overflow
2个回答
0
投票

html:

<div class="container">
  <div class="header">
    Very long text that should not wrap and be center aligned
  </div>
</div>

css:

body {
  margin: 200px;
}

.container {
  width: 100px;
  height: 50px;
  background-color: #bbb;
  position: relative;      // add this
}

.header {
    white-space: nowrap;
    position: absolute;    // add this
    top: 50%;              // add this
    left: 50%;             // add this
    transform: translate(-50%, -50%);// add this
}

0
投票

使用文字缩进:

body {
  margin: 200px;
}

.container {
  width: 100px;
  height: 50px;
  background-color: #bbb;
  text-align: center;
}

.header {
  white-space: nowrap;
  text-indent: -8em;
}
<div class="container">
  <div class="header">
    Short Text
  </div>
  <div class="header">
    Very long text that should not wrap and be center aligned
  </div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.