bew5 bew5 - 1 month ago 9
CSS Question

CSS: position: absolute together with margin: auto for centering - How does that work?

I've seen that pattern for centering an element on a website in the code of someone else:



img {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}

<img src="https://placebear.com/200/300" alt="picture-one" />





It works fine. No doubt !

But I can not imagine what the CSS-code actually does.

I've seen similar code in which positioning was used to extend an child element to the size of it's parent.



#child {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: lime;
}

#wrap {
width: 100%;
height: 800px;
}

<div id="wrap">
<div id="child"></div>
</div>





But here it makes no sense to me.

Can someone explain me how these first shown technique work?

What the single properties do and how it finally accomplishes it's result?

I would appreciate it.

Answer

#child {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100px;
  width: 250px;
  margin: auto;
  background-color: lime;
}

#wrap {
  width: 100%;
  height: 800px;
}
<div id="wrap">
  <div id="child"></div>
</div>

It's because the image has its default width and height.

When you use

position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;

Element would get the window size and position the element inside of it.

#child {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100px;
  width: 250px;
  margin: auto;
  background-color: lime;
}

#wrap {
  width: 100%;
  height: 800px;
  position: relative;
}
<div id="wrap">
  <div id="child"></div>
</div>

So, if you put position relative to #wrap, the position absolute #child will adjust to the parent.

Hope it helps! Cheers!

Comments