
This is an example of an element with position: fixed;
applied to it, for this blog's article on the CSS property.
As background-attachment: fixed
is to background images, position: fixed
is to elements: it allows an element to be stuck in position relative to the page, allowing the rest of the content to scroll past it. It is usually applied to container elements, fixed headers and footers being a popular example. As with elements positioned absolute
, ordinary static
content will scroll underneath any fixed
content. One example is a “pull tab” on the side of this page, which keeps content out of the way until needed.
While I will leave the interactivity of such a feature to another article, positioning the tab itself is very easy. The markup is as follows:
<div id="fixed-pull-tab">
<img src="red-tab.png" style="float: right" alt="LEVI’S">
<p>This is an example of an element with <code>position: fixed;</code>
applied to it, for this blog’s article on the CSS property.
</div>
And the associated CSS – I have used box-shadow
on the image to emphasize the “layer above” nature of the fixed position div
:
div#fixed-pull-tab {
width: 300px;
border: 1px solid #000;
padding-left: 1em;
background-color: rgba(255, 255, 37, 0.7);
position: fixed;
left: -265px;
top: 200px;
}
div#fixed-pull-tab p {
margin-right: 70px;
}
div#fixed-pull-tab img {
box-shadow: 4px 4px 4px rgba(0, 0, 0, 0.33);
}
div#fixed-pull-tab:hover {
left: 0;
}
As with position: absolute
, fixed should be used carefully: the property makes it all too easy to create web page features that overlap and obscure page content.
Oddities: fixed element(s) inside a container
Under normal circumstances, an element with position: fixed
is removed from the flow of the document, and any position information provided to the element locates it relative to the <body>
, with no other options possible.
However, it is possible to place a position: fixed
element inside and relative to another, if that parent element is transformed. That is, given the following markup:
<div id="container">
<div id="fixed"></div>
</div>
The inner element can be “fixed” to its parent by using the following (sans vendor prefixes for the purposes of illustration):
#container {
transform: translateZ(0);
}
#fixed {
position: fixed;
}
This odd feature is actually part of the CSS spec, and supported in all modern browsers I've tested in (with the exception of IE 11): to my knowledge, Eric Meyer was the first to spot this possibility. I expect it will be very rarely used (most developers would prefer the far more common and well-known position-absolute-inside-a-relative-container technique), but it is worthwhile knowing.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.