div {
width: 300px;
height: 300px;
border:1px solid black;
}
h1 {
width: 300px;
transform: rotate(-90deg)
}
<div>
<h1>Hola</h1>
</div>
如果你尝试这个片段,你会看到 h1
被旋转并放置在 div 的中心(有道理,它们具有相同的宽度)
但是如何让它向左对齐呢? (灵活容器的宽度)
最佳答案
您可以相对于父级 div
绝对定位 h1
元素,然后使用 transform-origin
属性指定轴轮换应该发生。
在下面的代码片段中,元素位于父元素的底部,因为原点设置在左下角,所以元素的左下角 (h1
) 保持在其位置在旋转过程中。
现在由于旋转,元素会在旋转后离开父元素。要将其放回原位,请将 translateY(100%)
添加到转换堆栈。添加 text-align: right
以将内容设置在左上角。 text-align
使它看起来比实际更古怪,但否则很难定位在 left-top
。
div {
position: relative;
width: 300px;
height: 300px;
border: 1px solid black;
}
h1 {
position: absolute;
display: inline-block;
bottom: 0px;
width: 300px;
text-align: right;
transform: rotate(-90deg) translateY(100%);
border: 1px solid;
transform-origin: left bottom;
}
div, h1 {
margin: 0px;
padding: 0px;
}
<div>
<h1>Hola</h1>
</div>
future 访客须知:与使用静态值进行定位不同,这种使用 translateY()
的解决方案即使内容长度增加也能自动适应或像下面的代码片段一样跨越多行。同样,唯一的缺点是文本将右对齐。
div {
position: relative;
display: inline-block;
width: 250px;
height: 250px;
border: 1px solid black;
}
h1 {
position: absolute;
display: inline-block;
bottom: 0px;
width: 250px;
text-align: right;
transform: rotate(-90deg) translateY(100%);
border: 1px solid;
transform-origin: left bottom;
}
div,
h1 {
margin: 0px;
padding: 0px;
}
<div>
<h1>Halooo</h1>
</div>
<div>
<h1>Some lengthy content which wraps around</h1>
</div>
关于css - 与容器左侧对齐,元素旋转 -90 度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32602515/