Why does setting an element to be position:fixed
change its width? I know that HTML elements by default span the entire width of the browser window, but when I set the position on my header to be fixed, the <div>
shrinks to zero width. Why is this?
Trying width:auto
does not fix it, the <div>
still has zero width!
This example is taken from Code Academy "Build a Resume" project at the end of their Web Fundamentals course.
I have an HTML file like so:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
<title></title>
</head>
<body>
<div id="header"></div>
<div class="left"></div>
<div class="right"></div>
<div id="footer"></div>
</body>
</html>
and a CSS file like so:
div {
border: 5px solid red;
border-radius: 5px;
}
#header{
height:30px;
background-color:orange;
z-index:1;
}
#footer{
height:30px;
background-color:teal;
clear:both;
}
.left{
height:300px;
width:200px;
float:left;
}
.right{
height:300px;
width:200px;
float:right;
}
UPDATE: I noticed that setting width:100%
does keep the width all the way across the browser window. What is going on here? I've read Why does fixed positioning alter the width of an element? but am not sure how that applies here.
Edit: Thought I would move this up from the comments and try answering it here, to give more direction on where I'm confused: "Yes, it seems like "Whereas the position and dimensions of an element with position:absolute are relative to its containing block, the position and dimensions of an element with position:fixed are always relative to the initial containing block" is the key part. So I see that position:fixed will set the dimensions of my relative to the viewport, but isn't the viewport the whole browser window? So why does its size collapse to zero? And beyond that, why does width:auto not fix it but width:100% does make it span the whole horizontal length again?"
width:auto
is different from width:100%
. width:auto
will expand the width of the element to all horizontal space within its containing block. Since the space is on the inside of the containing block it doesn't count borders/padding/margins.
width:100%
does what width:auto
does and adds the width of the borders/padding/margins of the containing element. difference between width auto and width 100 percent provides a good visual demonstration.
So, when I set width:auto
on my position:fixed
element, and the position:fixed
shrink-wrapped the element's width to be that of its content (which was nothing), then the width automatically adjusted to be that of the containing element, which in this case was _________ (what? and why did it have a width of zero?).
When I set it to be width:100%
then it includes the padding/margins/border of _________ (what? and why did it expand to cover the whole page horizontally?).