Click to share! ⬇️

CSS Position Tutorial

In this tutorial we’re going to look at all the ways we can position elements on a web page. HTML documents have a specific flow, and learning how to position things means understanding how the flow works, how to break out of the flow, and how to get back in to the flow to arrange elements on the web page. When talking about positioning in CSS, we also need to talk about floats and floating elements. Floats allow designers to “hack” the normal page flow to move elements left or right, not just top down. CSS Positioning can allow designers to place elements anywhere they like with a high amount of accuracy.


The CSS Flow

In the introduction we talked a little bit about “Flow”. In CSS, this means that elements are rendered on the screen in the order they appeared in the HTML source code. This means top to bottom and left to right. We learned that in the Box Model that block level elements stack on top of each other and inline elements display next to each other. As a browser changes dimensions, block level elements dynamically grow and shrink to fit the full width of the page. Inline level elements wrap to new lines as needed.


This diagram shows how the block level <p>, <h2>, and <p> tags consume the full width of the page. The inline text only goes 60 percent across or so.
block level elements full page width


When the browser resizes, the block level elements continue to take the full width of the page. The inline text re-flows to wrap onto new lines as needed.
inline content reflows as needed


This is what is meant by the flow of the document. Elements stack on top of each other and make room as needed. You can build entire websites without ever messing with the normal flow. To build more advanced layouts however, you need to start making use of floats and positioning. This is where you intentionally break the normal flow of elements to apply specific position attributes.


CSS Floats

When you use the float property in CSS, you are hacking into the normal document flow. It takes the values of left, right, none, or inherit. Floats allow the content to wrap around block elements and can be used to build multi-column layouts, navigation toolbars from lists, and other interesting effects. We can insert an image into our page to demonstrate no float, float left and float right.


Image with no float

img {
    padding-right: 10px;
}

inline image no float normal flow


Image with float left

img {
    padding-right: 10px;
    float: left;
}

inling image float left


Image with float right

inling image float right

So we can see that the float property is quite useful right away. We can use it to move an image to the left or right and let text wrap around it. This helps to make better use of space on the page. Here are some key points to understand about float.

  • A floated element is removed from the normal flow: When you apply a float to an element on the page, that html element is now removed from the normal page flow. Confusingly however, that element will continue to have an effect on any surrounding content. Think of it like an island in a river. The island is not in the flow of the river, but the river still needs to flow around the island.
  • A floated element stays in its containing element: The floated element stays in the content area of the box model for the containing element.
  • The entire element box is moved: When an element floats, the entire element box from outer edge to outer edge is effected.

Block Level Float vs Inline Float

Floats can be applied to both inline level elements and block level elements. For example, we can float a <span> element which is inline.
how to float an inline text element
html

<body>
    <div class="container">
        <p><span>Note! This is some important text!</span>Lorem ipsum dolor...</p>
    </div>
</body>

css

span {
    float: right;
    margin: 15px;
    width: 150px;
    background-color: lightcoral;
    padding: 40px;
}

That’s a pretty cool effect. There are a few things to keep in mind when floating text elements. You should set the width property otherwise the content area of the box expands to its widest possible width. This is because inline elements that have a float set behave as if they are block level elements. They will it follow the display rules for block-level elements, with margins rendered on all four sides. Additionally, margins on floated elements do not collapse like they do in the normal flow.


Block Level Floats

Now we can see an example of a block level float where we take a <p> element and float it to the left.
html

<body>
    <div class="container">
        <h2>Paragraph Block Level Float</h2>
        <p>
            Expedita dolorem voluptatem quibusdam...
        </p>
        <p class="pfloat">Lorem ipsum dolor sit amet...
        </p>
        <p>
            Expedita dolorem voluptatem quibusdam...
        </p>
    </div>
</body>

css

.pfloat {
    float: left;
    width: 400px;
    border: 2px solid lightcoral;
}

paragraph float left

Another neat effect. The paragraph moves to the left and the paragraph that comes after it in the html source, now wraps around it. In the normal flow, these two paragraphs stack on top of each other, but remember that once that float is applied, the element is no longer part of the normal flow. Again, you must set the width property otherwise the width of the floated element will fill all of the available width of the browser window or other containing element.


How To Clear Floats

Like we now know, when you use a float the normal document flow is hacked or turned off. There must be a way to turn it back on right? Indeed there is. It is by using the clear property. Applying the clear property allows you to say, “Ok – let’s turn the normal document flow back on”. In other words, you want the next element in the document to clear the bottom of the floated element. Let’s see why we really need that clear property. Consider this markup:

html

<body>
    <div class="container">

        <img src="city.png" width="350">

        <p>The image here does not have any float property.</p>
        
    </div>
</body>

image stacked on paragraph no float

That’s about what we would expect right? We see the image, and then on the next line we see the paragraph. Well, now you think, “Hmm, it might be nice to see that image moved to the right. Of course you know how to do that so you happily go off and apply a float:right to that image! Let’s see what happens.
css

img {
    float: right;
}

image float right no clearing

Say What?! The <p> tag clearly comes *after* the <img> tag in our html. You likely just wanted that image to move to the right, but did not want the paragraph to change its position on the page. This is where clear comes in. We need to somehow tell the paragraph, “hey – don’t show yourself on the page until you get past any floating elements”. That is what we mean by clearing floats. Since we applied a float:right to the image, we can apply a clear:right to the paragraph.
css

p {
    clear: right;
}

p tag with clear right applied

You can also just simply use clear:both which is especially useful when you have several floated elements, and you want to make sure an element starts below all of them. Imagine we now have two images on the page and one is going to float left while the other floats right. In addition, the second image is taller than the first. Let’s see what happens with the clear property in that scenario.
html

<body>
    <div class="container">

        <img class="city" src="city.png" width="200">

        <img class="cave" src="cave.png" width="400">

        <h2>City is float:left - Cave is float:right</h2>

    </div>
</body>

With no clearing on that <h2> element, look at how jumbled this layout is.
two floats no clears is bad

Now let’s apply a clear:left to the <h2> and see the effect.

h2 {
    clear: left;
}

two floats and clear left

Ok that’s a little better, but not quite right. Since we are only clearing the left float, the <h2> shows up right after the element it clears (The City). In this case we want to clear both floated elements. When we fix that clear property, things look much better.
two floats clear both good

The <h2> now clears both the City, and the Cave floated images.


How To Float Multiple Elements

Floating multiple elements can be used to create various effects on the web page. Two common effects you can create are the multi column layout, and turning a <ul> list of links into a horizontal menu. When several elements float, they will never overlap. Floating elements will always float as far to the left or right as they can, and as high up on the page as they can. Let’s start by placing four paragraphs in the html, and inside of each <p> tag will be an image. Remember, a <p> tag is a block level element so several of them will stack on top of each other and take up the full width of the browser. When we start with no float at all, here is what we get.
html

<body>
    <div class="container">

        <p><img class="city" src="city.png" width="150"></p>

        <p><img class="cave" src="cave.png" width="150"></p>

        <p><img class="lake" src="lake.png" width="150"></p>

        <p><img class="building" src="building.png" width="150"></p>

    </div>
</body>

four paragraphs with image inside

Now, we can start playing with the float property on the paragraphs. First, we just do a simple float:left.

p {
    float: left;
}

four html elements float left

Pretty cool! We should add some space in between those paragraphs. We can do this with margin.

p {
    float: left;
    margin: .4%;
}

multiple floats with margin

Very nice! Lastly, we can try setting float to right instead of left to see how that effects the layout of the web page.

p {
    float: right;
    margin: .4%;
}

multiple elements float right

Very interesting! This demonstrates an important concept with floats. The browser applies the float to multiple elements in a top down order. Clearly in our html markup, the order of the images in the <p> tags is City, Cave, Lake, and Building. Notice that when we float to the right, the order appears different on the page. This is because the browser sees the City first, and floats to the right, then it sees the Cave and floats to the right, and so on. This gives us the effect we see above.


Using Floats With <ul> and <li>

You are likely familiar with the look of an unordered list in HTML. Here is just a collection of CSS related links in an unordered list.

<body>
    <div class="container">
        <ul>
            <li><a href="#">Bootstrap</a></li>
            <li><a href="#">Animate.css</a></li>
            <li><a href="#">Normalize.css</a></li>
            <li><a href="#">Bulma</a></li>
            <li><a href="#">Hover</a></li>
            <li><a href="#">Tailwindcss</a></li>
            <li><a href="#">basscss</a></li>
        </ul>
    </div>
</body>

ul of links

Let’s turn that list of links into a cool navigation menu using CSS and floats.

First, we have to remove the bullet styling of the default <ul>.

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

remove bullets with list-style-type none

Now, we float each <li> element to the left.

ul li {
    float: left;
}

ul li float left example

Now, make each link in the list a block level element and add some margin and padding.

ul li a {
    display: block;
    padding: 5px;
    margin: 5px;
}

making a navigation menu with css

Lastly, add styles as you wish. We removed a couple of links for brevity.

ul li a {
    display: block;
    padding: 5px;
    margin: 5px;
    height: 50px;
    width: 120px;
    text-align: center;
    line-height: 50px;
    color: #fff;
    background: #2f3036;
    text-decoration: none;
    border-radius: 30px 30px 0 0;
}

navigation menu using float


How To Contain Floats

Floats protrude from the element they are contained within. This is by design. What do we mean by this? Well think of an image inside of a wrapping <p> tag. If there is no other text or content to give that <p> tag some height, then the image will hang out of that element. This example shows what we mean by that.
html

<body>
    <div class="container">
        <p><img class="lake" src="lake.png" width="300"></p>
    </div>
</body>

css

img {
    float: left;
}

image hanging out of a wrapping element

What we actually want is to have the wrapping element fully contain the image which is floated. To fix this, simply add overflow:auto to the wrapping or containing element.

p {
    overflow: auto;
}

contain float with overflow auto


Two Columns Using Floats

Floats are often used for entire sections of page layout. Let’s set up a two column layout using floats for some practice. We can start off with this basic markup.
html

<body>
    <div class="container">
        <section>
            <img src="design.png" width="170">
            Lorem ipsum dolor sit, amet consectetur adipisicing elit...
        </section>
        <section>
            <img src="dunes.png" width="170">
            Lorem ipsum dolor sit, amet consectetur adipisicing elit...
        </section>
    </div>
</body>

two section tags stacked

That is pretty basic. We have two <section> elements and they simply stack on top of each other. Now we can make it a two column layout.
css

section {
    float: left;
    width: 45%;
}

With just that simple little addition, we see the layout go from stacked to a column presentation which looks pretty nice!
two column layout using float


Positioning Elements Using CSS

We spent a good amount of time looking at flow in html and page rendering as well as floats. This is because if we don’t understand how those two concepts work, then we are going to be stuck in the mud regarding positioning elements using the static, relative, absolute, fixed, and inherit values. When positioning elements, they can be positioned relative to where they would have appeared normally in the flow, or taken out of the flow entirely and placed at a specific spot on the web page. All of this is done with the position property.


Position Static

By default all elements on the web page are using position:static without even needed to specify it. This is the normal positioning method which is what is used in the normal document flow. Chances are, you’ll never need to specify position:static.


Position Relative

If you assign position:relative to an element, what that does is allow you to offset the box precisely to the top, right, bottom, or left by a given amount relative to its original position in the document flow. The space that element would have occupied is preserved and continues to have an effect on the layout of surrounding content.

To demonstrate the position Relative technique, we will use the following markup. We remove the floats from our <section> elements so they now stack on top of each other. We also assign a width to the wrapping div, and set the margin to auto so that our <section> elements line up right in the center of the page.
html

<html>

<head>
    <title>CSS Positioning Tutorial</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
    <div class="container">
        <section class="one">
            <img src="berries.png" width="200">
            Lorem ipsum dolor sit...
        </section>
        <section class="two">
            <img src="forest.png" width="200">
            Lorem ipsum dolor sit...
        </section>
        <section class="three">
            <img src="fish.png" width="200">
            Lorem ipsum dolor sit...
        </section>
    </div>
</body>

</html>

css

section {
    border: 2px solid lightblue;
    padding: 10px;
    margin: 3px;
}

img {
    float: left;
    padding-right: 10px;
}

.container {
    width: 500px;
    margin: auto;
}

three section elements stacked

What we want to do now is apply a position:relative to the second <section> so that we can move it relative to where it would normally appear in the document flow. This following CSS says to offset that <section> 100 pixels from the left of where it would have normally appeared. This gives the effect of shifting the <section> 100 pixels to the right.

section.two {
    position: relative;
    left: 100px;
}

css position relative left example

You can also move it to the left by offsetting from the right.

section.two {
    position: relative;
    right: 100px;
}

css position relative right example

If we were to set either the top or bottom offset, the content would begin to overlap but you get the idea of how this works. It is important to note that when you use position:relative on an element, it is not removed from normal document flow. The element still occupies the original position in the document, it is just offset visually to the end-user. Position relative is very good if you want to simply tweak an element just a bit in the overall layout.

Consider the three sections are now back to a float layout where we have three columns. We could use this CSS to create a neat offset effect vertically now.

section.two {
    position: relative;
    top: 40px;
}

section.three {
    position: relative;
    top: 80px;
}

css position relative top

The key points to remember about Relative Positioning are:

  • The element remains in the normal document flow
  • The original space in the document is preserved
  • Be careful for overlapping content as you move the element

Position Absolute

The position:absolute value takes elements out of the normal document flow. This means the element can be placed absolutely anywhere on the web page that the designer chooses. Absolute positioning is likely the most commonly used and versatile of the various positioning methods. Absolutely positioned elements will continue to scroll with the page. The position:absolute value is most often used on an element which has a parent that has its positioning set to position:relative. It’s a little confusing, so let’s see an example.

We will start with just a <div> element which has an <img> and then an <h1> element like so.
html

<html>

<head>
    <title>CSS Positioning Tutorial</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
    <div class="container">
        <div id="banner">
            <img src="friends.png" width="100%">
            <h1>Hanging Out With Friends</h1>
        </div>
    </div>
</body>

</html>

image insdie a div with h1

With that in place, our goal is to take that <h1> headline and position it absolutely overlapping the image to give it a cool banner effect. It would almost be like the text itself is part of the banner. This is a two-step process. First, we assign position:relative to the parent of the element we want to absolutely position. So the parent of the <h1> is the div with an id of #banner. Once that is in place, we target the <h1> itself and apply position:absolute.


#banner {
    position: relative;
}

h1 {
    position: absolute;
    bottom: 10px;
    left: 140px;
}

css position absolute example

Looks pretty good! Absolutely positioned elements work in conjunction with containing blocks. Since overlap occurs with absolute positioning, you can make use of the z-index to adjust the stacking order of elements on the page to get the result you are looking for. So with Position Absolute, we can remember that:

  • The element is taken out of the normal document flow
  • The original space in the document is no longer preserved
  • Will often use with a parent element whose position is relative

Position Fixed

Position fixed is like taking an element and tacking it directly to the screen. In other words, the element stays fixed in one position in the window even when the user scrolls the page. Of course this means that fixed elements are taken out of the normal document flow and are positioned relative only to the browser window itself. Fixed positioning can get you in to trouble, so be careful with it. One use you might see with fixed positioning however is a fixed navigation bar. Let’s see an example of that.

Here is out HTML which now has a nav area near the top of the page.

<html>

<head>
    <title>CSS Positioning Tutorial</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
    <nav>
        <ul>
            <li>Link 1</li>
            <li>Link 2</li>
            <li>Link 3</li>
            <li>Link 4</li>
            <li>Link 5</li>
        </ul>
    </nav>
    <div class="container">
        <section>
            <img src="beach.png" width="200">
            Lorem ipsum dolor sit...
        </section>
        <section>
            <img src="berries.png" width="200">
            Lorem ipsum dolor sit...
        </section>
        <section>
            <img src="building.png" width="200">
            Lorem ipsum dolor sit...
        </section>
        <section>
            <img src="cave.png" width="200">
            Lorem ipsum dolor sit...
        </section>
        <section>
            <img src="city.png" width="200">
            Lorem ipsum dolor sit...
        </section>
        <section>
            <img src="concert.png" width="200">
            Lorem ipsum dolor sit...
        </section>
        <section>
            <img src="design.png" width="200">
            Lorem ipsum dolor sit...
        </section>
        <section>
            <img src="lake.png" width="200">
            Lorem ipsum dolor sit...
        </section>
        <section>
            <img src="fish.png" width="200">
            Lorem ipsum dolor sit...
        </section>
        <section>
            <img src="friends.png" width="200">
            Lorem ipsum dolor sit...
        </section>
    </div>
</body>

</html>

Our goal is to make this nav bar sticky to it sticks to the top of the page and is visible no matter what, even when scrolling. To do this, we can assign the nav a position of fixed, and then set the top to zero and the left to zero. This effectively sticks this navigation menu to the top of the page, and it will continue to be visible during scrolling. This is a common use case for a fixed positioning.

css

nav {
    width: 100%;
    background-color: #333;
    padding: 20px;
    position: fixed;
    top: 0;
    left: 0;
}

nav li {
    list-style-type: none;
    margin: 0 10px;
    color: white;
    float: left;
}

ul::after {
    display: block;
    content: "";
    clear: both;
}

And would you look at that?! Our nav bar is fixed right to the top of the page in a fixed location. Very nice!
nav bar fixed to top of page

In summary, fixed positioning has these traits:

  • The element is removed from normal document flow
  • Offset values for fixed elements are always relative to the viewport
  • The element retains position even during web page scrolling

CSS Position Tutorial Summary

This tutorial had us learning about how elements are rendered on a web page by the document flow. Elements can be removed and re inserted back into the flow by using floats and clears. We can also apply positioning to elements such as relative, absolute, and fixed to more precisely affect how and where elements are placed on the page. With this CSS based layout knowledge, you are ready to apply them to all kinds of web designs and page templates.

Click to share! ⬇️