居中缩放溢出文本

Centering scaled overflowing text

在我的 html/css 应用程序中,我有一个按钮的概念,本质上是 class .button 具有一堆适当的属性。这是一个简化的例子:

.button {
  width: 120px;
  height: 30px;
  line-height: 30px;
  background: yellow;
  text-align: center;
}
<div class="button">
  <div class="button-text">
    Button text
  </div>
</div>

少数地方需要显示的文字比较长,但还是要满满。由于 font-stretch 属性 不受支持,我使用 transform: scale,它满足我的需要 - 有点......除了上述之外,我还有:

.button {
  width: 120px;
  height: 30px;
  line-height: 30px;
  background: yellow;
  text-align: center;
}
.button-text {
  line-height: 30px;
  transform: scale(0.7, 1);
  white-space: nowrap;
}
<div class="button">
  <div class="button-text">
    Very long button text
  </div>
</div>

文本现在适合,但它没有居中,因为 div 中居中内容的位置是在应用转换之前计算的 - 请参阅此 jsfiddle 中的示例:https://jsfiddle.net/1xz1g634/1/

我可以 "make" 通过对 .button-text 应用负左边距来居中它,但是这是一个 hack,不同浏览器的边距必须不同。

我怎样才能使该文本普遍居中?理想情况下,无需求助于 javascript,但是,如果一切都失败了,我可以使用 javascript/jquery.

已为您修复。文本将自动居中,按钮将自动缩放。

CSS:

.button {
  display: inline-block;
  padding: 10px 20px;
  background: yellow;
  text-align: center;
}

.button-text {
  line-height: 30px;
  transform: scale(0.7, 1);
  white-space: nowrap;
}

HTML:

<div class="button">
  <div class="button-text">
    Very long button text
  </div>
</div>

https://jsfiddle.net/m7Lgmpn6/

很遗憾,长文本不居中的原因是正常溢出,所以text-align:center无效

缩放文本(尽管我觉得更小的 font-size {Codepen Demo} 可能更合适)不会覆盖 text-centering 因为转换只是视觉的。

我认为最佳解决方案(除了 font-sizing)是绝对定位内部文本元素并使用常用方法居中。

.button {
  width: 120px;
  height: 30px;
  line-height: 30px;
  background: yellow;
  text-align: center;
  position: relative;
  margin: 1em auto;
}
.button-text {
  position: absolute;
  top: 50%;
  left: 50%;
  line-height: 30px;
  transform: translate(-50%, -50%);
  white-space: nowrap;
  ;
}
.button-text.scaled {
  transform: translate(-50%, -50%) scale(0.7, 1);
}
<div class="button">
  <div class="button-text">
    Very Long Button Text
  </div>
</div>

<div class="button">
  <div class="button-text scaled">
    Very Long Button Text
  </div>
</div>

如果您将容器设置为 display:flex + justify-content:center,它会正确居中。

.button {
  width: 120px;
  height: 30px;
  background: yellow;
  display: flex;
  justify-content: center;
}
.button-text {
  line-height: 30px;
  transform: scale(0.7, 1);
  white-space: nowrap;
}
<div class="button">
  <div class="button-text">
    Very long button text
  </div>
</div>

您也可以使用 display: table 执行此操作...适用于 IE9。

实际上使用 filter: progid:DXImageTransform.Microsoft.Matrix 扩展到 IE8。

.button {
  width: 120px;
  height: 30px;
  background: yellow;
  display: table;
  text-align: center;
}
.button-text {
  display: table-cell;
  line-height: 30px;
  transform: scale(0.7, 1);
  white-space: nowrap;
}
<div class="button">
  <div class="button-text">
    Very long button text
  </div>
</div>