Crashalot
Crashalot

Reputation: 34523

Center absolute div under its parent using percentages not absolute values

This, this, and this question were similar but did not help.

The goal is to center an element under its parent using percentages, not absolute values. This way, position values do not need to change if sizes change.

The hover element below is centered under outer, but positioning requires absolute values that depend on the sizes of hover and outer. If either change, the position values must change.

Can centering underneath a parent be achieved with percentages?

Codepen: https://codepen.io/anon/pen/dadjpg

<div id="outer">
  <div id="hover"></div>
</div>

#outer {
  width: 200px;
  height: 200px;
  background: blue;
  position: relative;
}

#hover {
  width: 50px;
  height: 50px;
  background: yellow;
  position: absolute;
  margin: auto;
  left: 75px;
  bottom: -50px;
}

Upvotes: 0

Views: 47

Answers (2)

Hiren Vaghasiya
Hiren Vaghasiya

Reputation: 5544

You can also use top:100%; left:0px; right:0px; margin:0px auto;

#outer {
  width: 200px;
  height: 200px;
  background: blue;
  position: relative;
}

#hover {
  width: 50px;
  height: 50px;
  background: yellow;
  position: absolute;
  left:0px;
  right:0px;
  top:100%;
  margin:0px auto;
}
<div id="outer">
  <div id="hover"></div>
</div>

Upvotes: 2

Temani Afif
Temani Afif

Reputation: 273750

You can use top:100% to move the element to the bottom then simply combine left:50% with translateX(-50%) to center:

#outer {
  width: 200px;
  height: 200px;
  background: blue;
  position: relative;
}

#hover {
  width: 50px;
  height: 50px;
  background: yellow;
  position: absolute;
  left:50%;
  transform:translateX(-50%);
  top:100%;
}
<div id="outer">
  <div id="hover"></div>
</div>

Same logic considering bottom:0

#outer {
  width: 200px;
  height: 200px;
  background: blue;
  position: relative;
}

#hover {
  width: 50px;
  height: 50px;
  background: yellow;
  position: absolute;
  bottom:0;
  left:50%;
  transform:translate(-50%,100%);
}
<div id="outer">
  <div id="hover"></div>
</div>

Another idea is to consider flexbox to center inside the element then translate to make the element outside:

#outer {
  width: 200px;
  height: 200px;
  background: blue;
  position: relative;
  display:flex;
}

#hover {
  width: 50px;
  height: 50px;
  background: yellow;
  margin:auto auto 0;
  transform:translateY(100%);
}
<div id="outer">
  <div id="hover"></div>
</div>

Upvotes: 1

Related Questions