I am trying to make a layout with:
- A header (gray block in the snippet)
- A body (lime borrder)
- Main body content ( blocks with red border)
If you scroll horizontally, then the header should not scroll, it should be full width and stay in view. If you scroll vertically, then the header should scroll off the page as usual. The height of the header is dynamic, and fits the content within it (this SO answer works with a fixed height)..
The <main>
element is allowed to be wider than the viewport, but the header is always the viewport width.
The reason I dont add max-width: 100%; overflow-x: auto
on the <main>
element (like this SO answer, is because then the horizontal scroll appears at the bottom of the element, and then say one is reading the first block, and you wish to scroll horizontally, you have to scroll to the bottom of the main element to see the horizontal scroll bar, scroll to the side, then scroll back up. I wish to have the horizontal scroll bar always present if main is wider than the view port.
I have tried position: sticky/fixed on the header but could not get it to work.
I would prefer not to use JavaScript if possible.
header {
padding: 32px;
background: gray;
width: 100%;
}
main {
border: 2px solid lime;
min-width: 100%;
}
div {
height: 200px;
width: 120%; /* make it overflow horizontally */
display: flex;
align-items: center;
justify-content: center;
border: 2px solid red;
}
<header>The Header should not scroll horizntally<br>(is dynamic height)</header>
<main>
<div>content 1</div>
<div>content 2</div>
<div>content 3</div>
<div>content 4</div>
<div>content 5</div>
<div>content 6</div>
</main>