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;
}
Relative - the element is positioned relative to its normal position. Absolute - the element is positioned absolutely to its first positioned parent. Fixed - the element is positioned related to the browser window. Sticky - the element is positioned based on the user's scroll position.
As a special, use “relative” positioning with no displacement (just setting position: relative ) to make an element a frame of reference, so that you can use “absolute” positioning for elements that are inside it (in markup).
Absolute positioning defines the position of a given bounding box from the top and left side margins of the web page. This not only allows objects to be placed in an exact location, it also allows objects to be placed one on top of another.
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.
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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With