SnowboardBruin
SnowboardBruin

Reputation: 3685

How to center and overlap DIVs

I have 2 DIVs, that I want to center and overlap. The smaller one is to lay on top of the bigger one.

It works great at full-screen, but if I decrease the browser size, the top/smaller one moves to the left.

<div style="position: relative; top: 160px; border: thin solid gray; border-radius: 10px; width: 300px; height: 64px; margin-left: auto; margin-right: auto; z-index: 1; background: url(...); background-repeat:no-repeat; background-position:top; background-color: #4b2f84">&nbsp;</div>
<div style="position: absolute; top: 200px; left: 15%; width: 70%; background: white; border: thin solid gray; border-radius: 10px; height: 500px; padding: 50px 30px; margin: auto">something
</div>

Upvotes: 0

Views: 1497

Answers (1)

Zze
Zze

Reputation: 18805

I like to use left: 50%; combined with transform: translateX(-50%); when trying to center and overlap content.

The content is offset 50% to the left, and then -50% of its width to the left.. or (this.left == parent.x + parent.width* 0.5 - this.width*0.5)

#div1 {
  position: relative;
  top: 160px;
  border: thin solid gray;
  border-radius: 10px;
  width: 300px;
  height: 64px;
  margin-left: auto;
  margin-right: auto;
  z-index: 1;
  background: url(...);
  background-repeat: no-repeat;
  background-position: top;
  background-color: #4b2f84
}
#div2 {
  position: absolute;
  top: 200px;
  left: 50%;
  transform: translateX(-50%);
  width: 70%;
  background: white;
  border: thin solid gray;
  border-radius: 10px;
  height: 500px;
  padding: 50px 30px;
  margin: auto
}
<div id="div1">&nbsp;</div>
<div id="div2">something</div>

Upvotes: 1

Related Questions