user304117
user304117

Reputation:

Vertically centred div which increases parent height

There is a div which has a dynamic content. The height of the parent is 100% of the body and child is unknown. translateY(-50%) technique works good only if a child content height is less than parent. But if it's more child div(green) starts to overflow the parent (yellow) as on below image. enter image description here What's a proper way to set parent div increase the height and add some paddings.

.body {
  height: 300px;
  background: red;
}
.parent {
  height: 100%;
  position: relative;
  background: rgb(105, 199, 115);
   
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: green;
  width: 200px;
 }
<div class="body">
  <div class="parent">
    <div class="child">
      Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, 
    </div>
  </div>
</div>

Upvotes: 2

Views: 841

Answers (1)

Mortie
Mortie

Reputation: 404

Why positions?!
You can center div With this:
I use this for center a div with dynamic height in it's parent:

<style>
    .body {
        height: 300px;
        background: red;
        display:table;
        width: 100%;
    }
    .parent {
        display:table-cell; 
        vertical-align: middle;
        background: rgb(105, 199, 115);

    }
    .child {

        background: green;
        width: 200px;
        margin: auto;
    }
</style>
<div class="body">
    <div class="parent">
        <div class="child">
            Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, 
        </div>
    </div>
</div>

Upvotes: 3

Related Questions