S
S
Stanislav2021-02-28 18:11:18
css
Stanislav, 2021-02-28 18:11:18

How does chrome calculate margin:auto?

Good afternoon, forum users!

Faced with an incomprehensible situation - two blocks, one in the other. The first is relative, the second is absolute with margin:auto. Depending on the height of the second block, chrome either sets (calculates) the same margin on top and bottom, or considers that the margin is different.

For example, height:50%:
603bb1d742858798481023.jpeg

And for height:27%:
603bb22b98b5f285197056.jpeg

Of course, the difference is small, but it is there.
It is not clear why the block behaves this way?
Thank you!

<style>
*{margin:0;padding:0;}
body, html {width:100%;height:100%;}

#q1{
background-color:#0066CC;
position:relative;
height:100%;
width:100%;
}

#q2{
position:absolute;
height:50%;
width:100%;
top:0;
bottom:0;
margin:auto;
background-color:#3399CC;
}

</style>

<div id="q1">
<div id="q2"></div>
</div>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Yakimchuk, 2021-02-28
@yakimchuk-ry

I did not understand until the end of the question, but there are two points:
1. Do not combine top and bottom with margin (top & bottom) for absolute elements, because this is the solution to the same task in different ways, and, frankly, I don’t even know how the browser will behave
2. margin: auto takes the element's container and "centers" it by adding margin on both sides of the element equally, so your 27% margin came out more than the height of the element itself. But again, strange thing, because for the absolute + top & bottom it should have stretched it to full screen, and not made a margin.
It's thinking out loud, maybe something will help.

S
Stanislav, 2021-02-28
@Stas2021

Thank you!
The issue is that at 50% the top and bottom margins are the same (for example, 326.500). At 27% - different (top 476.688, bottom 476.703).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question