CodeinWP CodeinWP

Using Absolute Positioning in CSS

Once you start to become more experienced with CSS, one concept that will help you greatly is use of the position property, in particular with a value of absolute.

Some of the benefits of using absolutely positioned elements in your layouts include:

  • Aside from a few IE bugs, very good cross-browser support
  • Less dependence on floats, which can be problematic
  • Less dependence on margins, which can be a bit buggy in older IE

Drawbacks of absolutely positioned elements include:

  • The positioned elements are removed from the natural document flow
  • Can cause maintenance problems if you have to add other elements near the positioned one

The Basic Syntax

To position an element absolutely, you need to do a few things. Here’s the code, then a basic explanation:

First, some basic HTML:

<div class="box">

  <div class="inner-box">
  <p>dummy content</p>
  </div>

</div>

Now the CSS:

.box {
  position: relative;
}

.inner-box {
  position: absolute;
  top: 20px;
  left: 50px;
}

(In this example, I’ve omitted some values that would otherwise be necessary, like width and/or height.)

First, you need to create what’s referred to as a positioning context. In this case, the positioning context is the .box element. We do this by adding position: relative to that element.

Next, we need to absolutely position the inner element. We do this by setting position: absolute.

Lastly, we tell the browser where exactly we want the inner element to be placed in relation to the outer element. This is done using four possible properties: top, right, bottom, and left. In this example, I’m using two (which is enough). The inner element, by default, starts out in the top left corner of the outer element, then gets positioned 20px down from the top and 50px in from the left.

What Happens if You Don’t Set a Positioning Context?

Absolute positioning doesn’t require a ‘relative’ element (as set on the .box element above). If you absolutely position an element without a positioning context, then the positioning will take place relative to the entire page. (The exception is if you don’t specify any top, bottom, left, or right values. In that case, even if there is no positioning context, the context will automatically become the immediate container element, and the element will still be in flow.)

The lack of positioning context is probably the biggest cause for problems with people new to CSS positioning. A CSS beginner may decide to try setting the position of an element to “absolute”, then after setting top and left values, notice that the element will either get pushed all the way to the left or all the way to the top, or both. And it will be outside of its container element. This might cause a beginner to give up and not ever use that property.

So understanding how the positioned parent affects the absolutely positioned child will help greatly because this is a very useful technique to be familiar with.

Bonus Tip: Sizing Without Width or Height

Here’s a bonus tip that probably not a lot of people know about. You can actually define the dimensions of any absolutely positioned element using the top, left, bottom, and right values alone, without any content in the element and without width or height values.

Here’s an example using the same HTML from above:

.box {
  position: relative;
  width: 400px;
  height: 400px;
}

.inner-box {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

This will cause the inner element to fill the outer element’s content area. Here’s a JSBin with some exaggerated borders, so you can see how this works:

Conclusion

Don’t be afraid of CSS positioning if you don’t understand it at first, or if you run into problems. It’s a useful technique that, when understood well, will help you avoid a number of problems that can occur from having too many floats or too many margin settings.

You can read more on positioning on SitePoint’s reference.

24 Responses

  1. Adam says:

    I agree, don’t be afraid of it! But the biggest tip I can give to newcomers to CSS is to not position anything. Get a grasp on the box-model and how things work in CSS first, and then start playing around, after reading simple tutorials like this one, with positioning.

    Far too many times you can look at the code of a CSS newbie and see that every single block level element has position’: whatever on it because they simply don’t understand what that rule does/will do.

  2. Emma says:

    This is a nice ‘from scratch’ explanation. I do like using absolute positioning for certain elements. Not sure where my phobia has come from but I always feel like its going to be a bit ‘hit and miss’ which of course, it isn’t. Thats the ‘absolute’ point. I often encounter problems when using floats and think they are used too often. Adam is right, us newbies often use too many css definitions that we don’t actually need!

  3. Luca says:

    cool! i didn’t know the bonus tip! there’s always something to learn :)

  4. msankhala says:

    Its really cool stuff. Not only css beginners but also many professional web developer don’t know it.

  5. کیش says:

    hi all CSS experts,
    i want to change only vertical position of background image and remain the horizontal position i already set before.

    how can i do it:

    help asps
    thanks
    Nayana Adassuriya

    • Just declare the background position with the same horizontal value. For example, if the previous position is:

      
      .element {
          background-position: 20px 50px;
      }
      

      The first value is the horizontal position. So the new rule would be:

      
      .element {
          background-position: 20px 100px;
      }
      

      So now the horizontal has stayed the same, but the vertical has upgraded to “100px”.

  6. J says:

    CSS is a stupid mess.

  7. Adeel Ahmed says:

    I have developed a whole site with absolute positioning.It is good for fast development

  8. Steve Hunt says:

    This article saved my sanity. I’d created page that looked fine in IE but awful in any other browser. However just by adding the relative position in my wrapper div the site now looks fine on every other browser I try.

  9. steve says:

    Thx …. helped me learn and fix the exact problem you were addressing (absolute positioning relative to the page, not the container).

  10. Todd says:

    You can add to your “tip” by showing the power of using percentages which can come in handy for custom justification and sizing of a box in relation to a parent, for instance as a random example

    
    .center-in-box-bottom {
        position:absolute; 
        top: 75%; 
        bottom: -25%; 
        left:45%; 
        right: 45%;
    }
    
    
    <div class="center-in-box-bottom"></div>
    

    Which would then create a div 1/2 the height and 10% of the parents width centered horizontally and centered vertically using bottom of the parent

    Just one example, but it comes in handy from time to time.

  11. Tnx . helped me . nice tutorial

  12. Emmad says:

    Thanks for a good article. What do you think of using this method to position input fields in a form. Do you see any problems I need to watch out for? Thanks.

    • I would not recommend doing that with form elements. Remember that absolutely positioned elements will not have layout (that is, they don’t take up space in the document), so if you position other elements inside the form, you’ll have to position all of those elements absolutely too.

      Form elements can be annoying to lay out at times, but I would not recommend using abs. pos. for them.

  13. Pete Haas says:

    Thanks for this. I never use absolute positioning, and was stuck until I made my containing div relative. Much appreciated.

  14. Bill S. says:

    Very helpful. The ‘Bonus Tip’ was new for me, and exactly what I needed. I only required the Absolute Div width to conform to the containing div, so left:0; right:0; did the trick. Thanks.

  15. Ali says:

    Hi,
    If I want to make my site mobile friendly and still need to use relative and absolute positioning. Would it be possible to use percentages for “top”, “left”, etc.? I tried it on a project I am working on but it didn’t work unfortunately? Thanks!

  16. Nick says:

    Hey, nice little article… I’ve solved an alignment problem setting div.fields to position: absolute; top: auto: left: auto;. It basically brings the div.fields back into top alignment with the img.image element, see sample HTML below.

    Previously div.fields were position: relative; and this caused that inline-block to drop slightly.

    // Set the positioning context

    
    li.container {position: relative;}
    
    
    
    
    
      
      
        
        
        
      
    
    
    

    My question though, is how come the position: absolute; top: auto: left: auto; is bringing it back into alignment? This also works with position: absolute; and I always thought it would default to top: 0; left: 0;

    Thanks for any help you can give,

    Nick

    • Nick, something got mangled in there. Anyhow, “auto” is the initial/default value for top/left/bottom/right, which is a bit complicated to explain here, but I might write an article about it.

  17. Arkan Somar says:

    For me the only way to make the margins work is not using them. No margins nor paddings. I play with relative and absolute positioned. Top, left, bottom and right allow me to emulate the margins (these ones working). The combination of relatives (that follow the flow), and absolutes allows me to build a site that behaves as I set it from the biggest screen to the smallest. I forgot to mention that I float everything left in my common.CSS and set the font size to vw normaly.

    If I need to change where an element or group of elements are positioned I use the media queries.

  18. thanks
    i will share it

  19. Raja Thavamani says:

    Hi, Thanks Its Really Nice.. Its Working For Marker On Image With Mobile Responsive.. Thanks Again..!

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).