我有以下HTML:
<div class="outer">
<div class="inner rotate">Centered?</div>
</div>
div.outer
是一个狭窄的垂直条带。 div.inner
旋转90度。我想文字“居中?”显示在其容器div中居中。我事先不知道div的大小。
这很接近:http://jsfiddle.net/CCMyf/2/。您可以从jsfiddle看到文本在应用transform: rotate(-90deg)
样式之前是垂直居中的,但在之后有些偏移。当div.outer
很短时,这一点尤为明显。
是否可以在不事先知道任何尺寸的情况下垂直居中显示此文本?我没有找到解决此问题的任何transform-origin
值。
答案 0 :(得分:114)
关键是将位置顶部和左侧设置为50%,然后转换X并将Y转换为-50%。
.inner {
position: absolute;
top: 50%;
left: 50%;
}
.rotate {
transform: translateX(-50%) translateY(-50%) rotate(-90deg);
}
答案 1 :(得分:5)
回答这个问题可能有点晚了,但我偶然发现了同样的问题并找到了实现它的方法,通过添加另一个div。
<div class="outer">
<div class='middle'><span class="inner rotate">Centered?</span></div>
</div>
并在该中间元素上应用text-align: center
以及一些定位内容:
.middle {
margin-left: -200px;
width: 400px;
text-align: center;
position: relative;
left: 7px;
top: 50%;
line-height: 37px;
}
.inner
还获得display: inline-block;
以启用rotate
和text-align
属性。
这是相应的小提琴:http://jsfiddle.net/CCMyf/47/
答案 2 :(得分:2)
您可以将margin: 0 auto;
添加到“轮播”课程中以使文字居中。
.rotate {
-webkit-transform: rotate(-90deg);
-ff-transform: rotate(-90deg);
transform: rotate(-90deg);
width: 16px; /* transform: rotate() does not rotate the bounding box. */
margin: 0 auto;
}
答案 3 :(得分:2)
'bjnsn'的答案很好但不完美,因为当文本中包含空格时它会失败。例如,他使用'居中?'作为文本,但如果我们改变文本让我们假设'居中?或者不是'那么它将无法正常工作,并将占用空间后的下一行。 Ther不是为内部div块定义的宽度或高度。
.inner {
font-size: 13px;
font-color: #878787;
position: absolute;
top: 50%;
left: 50%;
background: #DDD;
}
https://jsfiddle.net/touqeer_shakeel/f1gfy1yy/ 但是我们可以通过将内部div宽度设置为等于外部div的高度,内部div的行高度等于外部div的宽度并使用align设置内部div的display flex属性来使整个文本居中对齐-items:center和justify-content:center properties。
.inner {
font-size: 13px;
font-color: #878787;
position: absolute;
top: 50%;
left: 50%;
display: flex;
justify-content:center;
align-items:center;
line-height:40px;
}
$('#height').on('change', function(e) {
$('.outer').css('height', $('#height').val() + 'px');
$('.inner').css('width', $('#height').val() + 'px');
});
答案 4 :(得分:0)
从margin-top: -7px;
删除:.inner
使垂直旋转的文字居中。它还使水平文本不居中。
只需删除上面的代码?
答案 5 :(得分:0)
您可以添加:
$('.inner').css('margin-top', $(this).parent().height() - 2*$(this).height());
到.on('change')
功能,如您所见:http://jsfiddle.net/darkajax/hVhbp/
答案 6 :(得分:0)
将文本在Y轴上旋转90度并居中的另一种方法是:
.rotate-centered {
top: 50%;
right: 50%;
position: absolute;
transform: scale(-1) translate(-50%, 50%);
writing-mode: vertical-lr;
}
<span class="rotate-centered">Text<span>
示例:https://codepen.io/wwwebman/pen/KKwqErL
但是由于IE / EDGE writing-mode
中的不良支持而无法在此处运行:
https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode