How to make min-width
and max-width
work in positioned elements?
What works
- The gray header must fill out 100% of the window width at all times
- The green/yellow elements must resize depending on window width (
min-width
/max-width
) - The blue header is an extension of the green header, but without the gray background
What doesn’t work
- The green/blue/yellow elements must follow the same width at all times when you resize the window (the blue element does not)
How to make the blue element work as described (without the gray background)? I’m open if there is a better solution 🙂
The blue header is fixed to min-width
https://jsfiddle.net/wahdr9j7/4/
:root {
--header-height: 50px;
--page-header-height: 50px;
--sidebar-width: 100px;
--content-width-min: 400px;
--content-width-max: 500px;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
}
header,
#sidebar {
position: fixed;
top: 0;
left: 0
}
/* this gray header has to fill up the full width */
header {
width: 100%;
height: var(--header-height);
background: gray;
}
header,
main {
padding-left: var(--sidebar-width);
}
#header {
height: 100%;
background: green;
}
#page_header {
position: absolute;
height: var(--page-header-height);
background: blue;
}
#sidebar {
width: var(--sidebar-width);
min-height: 100%;
background: red;
}
#header,
#page_header_content,
#content {
max-width: var(--content-width-max);
min-width: var(--content-width-min);
}
#content {
background: yellow;
}
main {
padding-top: calc(var(--header-height) + var(--page-header-height));
}
<header>
<div id="header">
main header
<div style="text-align:right">right-aligned</div>
</div>
<div id="page_header">
<div id="page_header_content">
page header
<div style="text-align:right">right-aligned</div>
</div>
</div>
</header>
<div id="sidebar">
sidebar
</div>
<main>
<div id="content">
content
<div style="text-align:right">right-aligned</div>
</div>
</main>
2
Answers
add these styles
The
absolute
positioned div should be nested in themin-width
div which should be set toposition: relative;
.Add your custom
--content-width
max
andmin
on#page_header
instead of#page_header_content
so it’s on the parent like the others.Set
#page_header
torelative
and#page_header_content
toabsolute
.Fiddle for your convenience: A fiddle for clarkk