【问题标题】:Text Centers Horizontally, But Not Vertically When Transformed文本水平居中,但转换时不垂直居中
【发布时间】:2016-07-18 19:29:08
【问题描述】:

我创建了两个矩形 div(需要保持 60 像素宽和 150 像素高),其中包含文本。文本是要在矩形中垂直对齐,所以我使用transform: rotate(-90deg)来垂直调整文本的角度。

我想让文本垂直并在框中居中。在垂直旋转文本之前,我使用display: tablevertical-align: middle 方法使文本居中。当文本是水平的时,这非常有效。但是,旋转内容后,文本不会保持居中。 CSS 仍然使文本居中,就好像它是水平的一样。

我尝试使用绝对/相对定位从顶部和左侧偏移文本,但是当我删除 display: tablevertical-align: center 属性时,文本消失了。

关于如何在保持表格属性的同时使垂直倾斜的文本居中的任何想法?任何意见将不胜感激。

小提琴:https://jsfiddle.net/sxchx6zm/3/

HTML

<div id="both">
    <div class="rectangle">
        <div class="vertical">Text Area 1</div>
    </div>  
    <div class="rectangle">
        <div class="vertical">Test Area 2</div>
    </div>   
</div>

CSS

.rectangle {
  height: 150px;
  width: 60px;
  background-color: #d3d3d3;
  border: 1px solid red;
  display: table;

}

.vertical {
  font-size: 16pt;
  height: 150px;
  max-width: 60px;
  display: table-cell;
  vertical-align: middle;
  transform: rotate(-90deg);
  white-space: nowrap;
}

【问题讨论】:

  • @Joum 我尝试了一些建议 - 它们都不符合我在删除 display 和 vertical-align 属性时文本消失的问题。另外,有些人建议在顶部添加一个设置的边距,我宁愿让它直接居中而不指定像素或百分比
  • @martin934 我唯一的选择是设置 position:relative ;对于 .vertical 类和顶部:Xpx;但是,这需要您为 .vertical 类设置固定宽度,但它会起作用。
  • @Aaron 我希望它直接居中的原因是因为文本长度并不总是相同,例如:jsfiddle.net/sxchx6zm/18。我每次都必须调整像素/百分比。如果要将其设置为始终直接居中,我将不必调整像素/百分比并“猜测”数字。我正在寻找解决这个问题的方法,但如果我找不到解决方案,那就行了。

标签: html css


【解决方案1】:

如果您可以为.vertical 设置width,而不是max-width,我就能找到一种方法。

如果您这样做,您只需将其添加到您的 CSS 中以获取 .vertical -- text-align:center;

这让你的 CSS 变成这样:

.rectangle {
  height: 150px;
  width: 60px;
  background-color: #d3d3d3;
  border: 1px solid red;
  display: table;
}

.vertical {
  font-size: 16pt;
  height: 150px;
  width: 60px; //modified
  display: table-cell;
  vertical-align: middle;
  transform: rotate(-90deg);
  white-space: nowrap;
  text-align : center; //added
}

请注意,您需要将文本水平和垂直居中,因此使用此解决方案。 这是更新的小提琴:https://jsfiddle.net/sxchx6zm/19/

【讨论】:

  • 谢谢,但现在盒子的宽度大约是 100px。我应该指定它们需要保持在 60px 的宽度
【解决方案2】:

这是一个不需要使用 CSS 表格的解决方案:

.rectangle {
  height: 150px;
  width: 60px;
  background-color: #d3d3d3;
  border: 1px solid red;
}

.vertical {
  text-align: center;
  font-size: 14pt;
  line-height: 150px;   /* assumes text takes one line only */
  white-space: nowrap;
  margin-left: -100%;   /* centers so that the element overflows to the */
  margin-right: -100%;  /* ... left and right of its parent equally */
  transform: rotate(-90deg);
}
<div class="rectangle">
  <div class="vertical">Test Area 1</div>
</div>

<div class="rectangle">
  <div class="vertical">Test Area two</div>
</div>

<div class="rectangle">
  <div class="vertical">Test Area THREE</div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 2012-03-14
    • 2017-06-28
    相关资源
    最近更新 更多