I have a very simple problem: I want to have multiple <section>
s inside a <main>
tag. Each of the sections should contain a child <div>
that is sticky so it is bound by the height of the section.
Now I have the problem that the <main>
needs overflow-x: hidden
to remove unwanted horizontal scrollbars (especially on Safari) but at the same time this line seems to disable the sticky elements. Any ideas how to solve this without JS?
This demo shows the problem. Uncomment the overflow
to see the difference.
<!DOCTYPE html>
<html>
<head>
<style>
main {
width: 100%;
height: auto;
min-height: 100vh;
/*overflow-x: hidden;*/
position: relative;
display: block;
}
section {
width: 100%;
min-height: 100vh;
background: green;
}
div {
position: sticky;
top: 0;
}
</style>
</head>
<body>
<main>
<section>
<div>
<p>Content goes here</p>
</div>
</section>
<section>
<div>
<p>Second content goes here</p>
</div>
</section>
</main>
</body>
</html>
CodePudding user response:
Position sticky normally doesn't work if parent element have overflow hidden property. Instead of main try to give "overflow-x: hidden" to the body
body
{
overflow-x: hidden;
}
CodePudding user response:
You may try below code,
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
padding: 0;
box-sizing: border-box;
overflow-x: hidden;
}
main {
width: 100%;
height: auto;
min-height: 100vh;
/*overflow-x: hidden;*/
position: relative;
display: block;
}
section {
width: 100%;
min-height: 100vh;
background: green;
}
div {
position: sticky;
top: 0;
}
</style>
</head>
<body>
<main>
<section>
<div>
<p>Content goes here</p>
</div>
</section>
<section>
<div>
<p>Second content goes here</p>
</div>
</section>
</main>
</body>
</html>
Note: Also you may use overflow: auto;
instead of overflow-x: hidden;
for this particular task only.
For your reference please visit below link: https://www.w3schools.com/css/css_overflow.asp