Search code examples
htmlcsspositioning

Is there a way to position something based on the centre of the screen (horizontally) with CSS?


I'm wondering if there's a simpler way to do this:

  1. Position something centre-screen horizontally (easy).
  2. Offset it's position from the centre.

I normally achieve this by making a <div> with a width double of the amount I want to offset by, set it to margin: auto; and then put my desired element within this floated either left or right. This works fine, I just thought there might be a shorter way.

An an example, I might want to have a <div> positioned 80px to the left of the centre of the screen, like this:

                   enter image description here


Solution

  • You can do something like this:

    body { position: relative }
    
    div {
      width: 300px;
      height: 250px;
    
      /* Origins from the screen center */
      position: absolute;
      top: 50%;
      left: 50%;
    
      margin-top: -125px; /* height / 2 */
      margin-left: -230px; /* (width / 2) - 80 */
      /* The margin left would be -150px but you want it to move 80 pixels to left */
    }
    

    Here's an online example: http://jsfiddle.net/B4rDJ/2/ (thanks Purmou!)