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

<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.


to_forum.gif

You are using a percentage for the width of the child element. Use a percentage for the margin as well.

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

Depending on browser requirements you could use flexbox

[php]
.one {
border: 2px solid green;
height: 200px;
width: 50%;
display: flex;
justify-content: center;
align-items: center;
}

.second {
border: 2px solid red;
width: 50%;
}

second
[/php] https://jsfiddle.net/4qs0jpuj/

Thanks,
I thought margin: auto is the ultimate center mechanism.

Thank you !

Sponsor our Newsletter | Privacy Policy | Terms of Service