我想要一個帶有一個粘性元素和一個非粘性元素的標題。因此,結構應該是這樣的:
body {
margin: 0;
height: 2000px;
}
header {
position: static;
border: 1px solid blue;
overflow: visible;
}
.sticky-yes {
position: sticky;
top: 0;
border: 1px solid blue;
}
.sticky-no {
position: relative;
top: 0;
border: 1px solid orange;
}
<header>
<div class="sticky-yes">Sticky</div>
<div class="sticky-no">Not sticky</div>
</header>
<div>... Rest of the webpage ...</div>
你可以用一點創造性的CSS來做到這一點。增加了一點維護,但確實粘上了元素。請注意,這里我調整了兩個元素的大小,并將其用作頁眉的基本高度。我還使用了框大小來避免在瀏覽器中放大的問題。
body {
margin: 0;
padding: 0;
font-size: 16px;
height: 2000px;
--sticky-height: 3rem;
--non-sticky-height: 2rem;
--header-height: calc(var(--sticky-height) + var(--non-sticky-height));
}
header {
box-sizing: border-box;
border: 1px solid cyan;
height: var( --header-height);
}
.sticky-yes {
box-sizing: border-box;
position: fixed;
top: 0;
border: 1px solid blue;
height: var(--sticky-height);
}
.sticky-no {
box-sizing: border-box;
position: relative;
top: var(--sticky-height);
height: var(--non-sticky-height);
border: 1px solid orange;
}
<header>
<div class="sticky-yes">Sticky</div>
<div class="sticky-no">No</div>
</header>