tags:

views:

41

answers:

4

How could I center the blue box inside the red one ? I see that the left side of the blue box is exactly in the middle of the red box, but I would like to center the whole blue box, not its left side. The dimensions of the boxes are not constant. I want to align regardless of boxes dimensions. Example to play with 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;
}

alt text

+1  A: 

You could add left:50px to #abs if that's all you want...

#abs {
    position: absolute;
    bottom: 15px;
    width: 300px;
    height: 200px;
    border: 1px solid blue;
    left:50px;
}
rebus
I mean that the dimensions of the boxes aren't known. I want to align regardless of boxes dimensions.
Misha Moroshko
+1  A: 

If you are going to define dimensions like that (200px x 300px and 300px x 400px), here's how it can be centered:

#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;
}
Brant
The dimensions are not constant. I edited the question.
Misha Moroshko
Are you trying to center the entire box? Or just the left/right centering?
Brant
A: 

This should work

#abs {
    position: absolute;
    left: auto;
    right: auto;
    bottom: 15px;
    width: 300px;
    height: 200px;
    border: 1px solid blue;
}
Happy
The left/right auto trick (like centering a div with margin) doesn't work here.
Brant
+2  A: 

If you're able to change the <span> tag to a <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 more automation for the enclosed box as less changes would be needed should you change the size of the container box.

Jonas