Alignment with relative and absolute positioning

How can I center the blue frame inside the red? I see that the left side of the blue box is exactly in the middle of the red square, but I would like to focus the whole blue box, and not on its left side. Box sizes are not constant. I want to align regardless of the size of the boxes. An example for the game is here . Thanks!

HTML:

<div id="rel"> <span id="abs">Why I'm not centered ?</span> </div> 

CSS

 #rel { position: relative; top: 10px; left: 20px; width: 400px; height: 300px; border: 1px solid red; text-align: center; } #abs { position: absolute; bottom: 15px; width: 300px; height: 200px; border: 1px solid blue; } 

Screenshothot

+6
html css css-position
source share
5 answers

If you can change the <span> to <div>

 <div id="rel"> <div id="abs">Why I'm not centered ?</div> </div> 

Then this piece of CSS should work.

 #rel { position: absolute; top: 10px; left: 20px; width: 400px; height: 300px; border: 1px solid red; text-align: center; } #abs { width: 300px; height: 200px; border: 1px solid blue; margin: auto; margin-top: 50px; } 

I think it’s better to use automation for a closed box, as less changes are needed if you change the size of the container.

+2
source share

You can add left:50px to #abs if that is all you want ...

 #abs { position: absolute; bottom: 15px; width: 300px; height: 200px; border: 1px solid blue; left:50px; } 
+1
source share

If you are going to define such sizes (200px x 300px and 300px x 400px), here's how to center it:

 #rel { position: relative; top: 10px; left: 20px; width: 400px; height: 300px; border: 1px solid red; text-align: center; } #abs { position: absolute; width: 300px; height: 200px; border: 1px solid blue; margin: 49px 0 0 49px; } 
+1
source share

You can check my solution here at http://jsfiddle.net/NN68Z/96/

I did the following for css

  #rel { position: relative; top: 10px; left: 20px; right: 20px; width: 400px; height: 300px; border: 1px solid red; text-align: center; display: table-cell; vertical-align: middle; } #abs { display: block; bottom: 15px; width: 300px; height: 200px; border: 1px solid blue; margin: 0 auto; } 
0
source share

This should work

 #abs { position: absolute; left: auto; right: auto; bottom: 15px; width: 300px; height: 200px; border: 1px solid blue; } 
-2
source share

All Articles