Yorick
Yorick

Reputation: 101

Center div in div vertically and horizontally, position absolute

So I want to center "innerDiv1" vertically and horizontally in "outerDiv".

"innerDiv1" has to be position absolute, so "innerDiv2" can over lap it.

I have tried line-height, this doesn't work because "outerDiv" can change size. Line-height doesn't react to percentage the way I want it to.

Here's my snippet:

html, body {
  margin: 0;
}

.wrapper {
  background: lightblue;
  width: 300px;
  height: 300px;
}

.outerDiv {
  background: red;
  height: 50%;
  width: 50%;
}

.innerDiv1 {
  background: seagreen;
  position: absolute;
}

.innerDiv2 {
  background: rgba(255,255,255,0.5);
  height: 100%;
}
<div class="wrapper">
  <div class="outerDiv">
    <div class="innerDiv1">Hello World!</div>
    <div class="innerDiv2"></div>
  </div>
</div>

Thanks for your help.

Upvotes: 0

Views: 4826

Answers (2)

cup_of
cup_of

Reputation: 6687

Add this to your css:

.outerDiv {
  position: relative;
}

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

Upvotes: -1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

See for yourself. See the comments in the CSS on what you need to include.

html, body {
  margin: 0;
}

.wrapper {
  background: lightblue;
  width: 300px;
  height: 300px;
  position: relative; /* 1. Add this. */
}

.outerDiv {
  background: red;
  height: 50%;
  width: 50%;
  position: absolute;
  top: 25%; /* 2. Add this. */
  left: 25%; /* 3. Add this. */
}

.innerDiv1 {
  background: seagreen;
  position: absolute; /* 4. Add this. */
  top: 50%; /* 5. Add this. */
  left: 50%; /* 6. Add this. */
  transform: translate(-50%, -50%); /* 7. Add this. */
  text-align: center; /* 8. Add this if you want the text to be centered. */
}

.innerDiv2 {
  background: rgba(255, 255, 255, 0.5);
  height: 100%;
  top: 50%;
  left: 50%;
}
<div class="wrapper">
  <div class="outerDiv">
    <div class="innerDiv1">Hello World!</div>
    <div class="innerDiv2"></div>
  </div>
</div>

Upvotes: 3

Related Questions