问题1:顶部有多余空间
粘性定位的元素保留在 DOM 流中 - 就像relative
定位元素确实如此。因此,那里的空间被h1.section__title
元素。
问题2:粘性元素在节的末尾超出了外面
这是因为,原来的高度h1
即使在旋转之后,元素仍然被考虑在那里。
因此,您需要首先确定粘性标题的确切宽度(旋转后将成为该元素的高度),然后将该宽度值设置为旋转后的元素的高度,如下所示:
$section-sticky-header-height: 145px;
.section__title {
display: inline-block;
margin-bottom: 0;
transform-origin: 0% 0%;
position: sticky;
top: 0;
left: 50px;
/* solves problem 1 */
float: left;
/* solves problem 2 */
transform: rotate(-90deg) translatex(-$section-sticky-header-height);
height: $section-sticky-header-height;
}
代码笔:https://codepen.io/anon/pen/arybWZ
Edit:
问题是我无法确定粘性标题的确切宽度,因为 h1 文本是可变的(客户端将通过 CMS 插入该文本)。有办法处理这个问题吗?如果可以的话不用Javascript
知道了。如果高度可变,您可以尝试这样做:
<h1 class="h1 mb-0 section__title">
<div class="rotation-outer">
<div class="rotation-inner">
<div class="rotation">
STICKY
</div>
</div>
</div>
</h1>
.section__title {
border: 1px solid; // for demo purpose
position: sticky;
top: 0;
float: left;
.rotation-outer {
display: table;
position: relative;
left: 50px;
.rotation-inner {
padding: 50% 0;
height: 0;
.rotation {
transform-origin: 0 0;
transform: rotate(-90deg) translate(-100%);
margin-top: -50%;
white-space: nowrap;
}
}
}
}
查看实际操作:https://codepen.io/anon/pen/BedREm
关于其工作原理,这里有一个很好的解释:CSS 中的旋转元素会正确影响其父元素的高度
Edit 2:
在该链接中我还发现了writing-mode: vertical-rl;
属性(在此答案中 stackoverflow.com/a/50406895/1252920)。您认为可能有更好的解决方案吗?我在 Codepen 中应用了它:codepen.io/anon/pen/JqyJWK?editors=1100 你觉得怎么样?
是的,您可以使用另一种甜蜜的选择。 :)
这里我稍微改变/优化了它:https://codepen.io/anon/pen/qGXPPe?editors=1100
但是,请注意vertical-lr
or vertical-rl
没有得到广泛支持。显然只在desktopChrome/Firefox/Opera 版本。See here。
因此,使用哪一个取决于您。就我个人而言,我不会使用writing-mode
由于缺乏浏览器支持。