'Position an element fixed without removing it from Document flow
I've three elements in my HTML code. I want to position the element fixed to the right side without removing it from the document flow.
<div class="container">
<header class="main-header">
</header>
<main class="main-content">
</main>
<footer class="main-footer">
</footer>
</div>
Here is the css code i'm using
.container {
display: grid;
grid-template-columns: 1fr 3fr;
grid-template-rows: auto auto;
}
.main-header{
grid-column: 1/2;
grid-row: 1/3;
/* Here i want this to be fixed (scrolling should not have any effect)*/
position: fixed;
}
position fixed remove it from the Document flow and everything look ugly. Can anybody tell me how to achieve this without using position:fixed; or without removing it from the document flow.
Solution 1:[1]
Add an additional wrapping element around the header and then apply position:sticky to the header.
I have assumed you meant fixed to the left rather than right since this seems to be what was in your examples.
* {
margin: 0;
}
.con {
display: grid;
grid-template-columns: 1fr 3fr;
grid-template-rows: auto auto;
}
.wrap {
background: gray
}
header {
color: white;
text-align: center;
grid-area: 1 / 1 / 3 / 2;
position: sticky;
top: 0;
}
main {
background: rgba(0, 0, 200, 0.4);
height: 2000px;
padding-top: 10px;
}
footer {
text-align: center;
background: black;
color: white;
}
<div class="con">
<div class="wrap">
<header>
<h2>Someone</h2>
<p>Lorem ipsem</p>
<p>lorem Ipsem</p>
<p>lorem ipsem</p>
</header>
</div>
<main>
<h1>Heading</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Recusandae molestias maiores voluptates, suscipit eveniet vitae harum id? Fugiat labore eligendi delectus, ipsum molestiae numquam ex inventore deleniti deserunt quia perspiciatis!</p>
<h2>heading 2</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis atque enim possimus error voluptas distinctio eos vel? Dolorem alias voluptas minus sunt asperiores consequuntur! Sit harum qui culpa ea assumenda!
</p>
<h2>heaing 2</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam ut reprehenderit vero perferendis aspernatur, rerum asperiores! Aperiam aliquam commodi quod dolores, unde optio repellat necessitatibus facere, laborum expedita enim soluta.
</p>
</main>
<footer>
<p>Made by Zullu</p>
</footer>
</div>
Solution 2:[2]
Just keep the header fixed and give .main-content a padding-top as big as the height of your header, or even a bit heigher for estetics.
.main-header{
grid-column: 1/2;
grid-row: 1/3;
/* Here i want this to be fixed (scrolling should not have any effect)*/
position: fixed;
top: 0;
height: 80px;
}
.main-content {
padding-top: 100px;
width: 100%;
float: left;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Paulie_D |
| Solution 2 |
