I am trying to get the title (h2) of a scrollable list to stay fixed in relation to that window, and that window only. When I try position:fixed
, the title is fixed in relation to the scrollable window, but also to the entire page. How do I get the fixed positioning to apply only to the scrollable list window?
HTML code
.sub-headlines {
position: relative;
height: 400px;
margin-top: 2%;
width: 55%;
overflow: auto;
border: 1px solid red;
}
.sub-headlines h2 {
width: 100%;
font-size: 80%;
text-align: center;
background-color: rgb(238, 253, 247);
z-index: 0;
}
.sub-headlines-title {
position: fixed;
}
.sub-headlines ul {
overflow: auto;
list-style: disc;
text-align: center;
line-height: 2;
z-index: -100;
}
<div div class="sub-headlines">
<h2>Recent Headlines in Aging Science</h2>
<div class="sub-headlines-list">
<ul>
<li>a</li>
<li>b</li>
<li>d</li>
<li>e</li>
<li>f</li>
<li>g</li>
</ul>
</div>
</div>
position: absolute;
is the choice for that. It relates to the next higher ancestor which has position: relative
. Use the top
/bottom
/left
/right
parameters to position it and/or width
/height
(also in percentage values) to define its size if it should be larger than its contents.
Keep in mind that elements with position: absolute;
(same as fixed
) don't occupy any space of their own, so they can overlap other elements. To avoid that, you can for example use padding
settings for the parent element or margin
for subsequent elements to create empty space behind the absolutely positioned child element.