How do I place an element at the center of its' ancestor?

Hi everyone,
My code consists of 2 elements. “One” is the ancestor and “second” is child.
I try to place “second” at the bottom of “one” in the middle of its’ width.
here is my code:

<!DOCTYPE html>
<html>
<head>
<style>
.one {
    position:relative;
    border: 2px solid green;
    height: 200px;
    width: 50%;
}

.second{
    position: absolute;
   border: 2px solid red;
   width: 50%;
   bottom: 0;
   margin: auto;
}
</style>
</head>
<body>
<div class="one">one</h2>

<div class="second">second<div>
</div>


</body>


The attached screenshot displays the result: “second” is placed at the bottom of “one” but fails to be at its’ middle.
Could anyone tell me why?>
Thanks.

Hi there deotpit,

does this help…

.second{
    position: absolute;
    border: 2px solid red;
    width: 50%;
    bottom: 0;
    left:50%;
    transform: translate(-50%,0);
 }

coothead

3 Likes

Assuming you correct the html you can also do it like this:

.second {
	position: absolute;
	border: 2px solid red;
	width: 50%;
	bottom: 0;
	margin: auto;
	left:0;
	right:0;
}

If you add left and right co-ordinates the fixed width absolute element will center with margin:auto.

2 Likes

Thanks a lot coothead. It works all right !
Glad to have learned something new from you but I’d rather focus at what I should know.
Always thought margin: auto centers everything but apparently my knowledge is not complete yet :frowning:

1 Like

Thank you so much PaulOB. You’re always so helpful and you’re always there when you’re needed :slight_smile:

1 Like

Margin:auto will centre ‘block’ elements that have a width defined (or intrinsic width in the case of replaced elements like images) also assuming there is room in their container to be centred.

For fixed width absolute elements you need to set the left and right co-ordinates to the edges of the containing block and then the fixed width element will center.

As an aside if you describe the top and bottom co-ordinates also then margin:auto will center vertically absolute elements of a fixed height (unlike static elements).

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.