How to create a child div stick to the bottom border of parent div with 50% inside the parent and 50% outside

Viewed 684

I want a child div to stick to the bottom of parent div on the border. Something like the div below. But I want that red div should always be on the center of the border vertically, meaning the child div should stick to the bottom border of parent div with 50% inside the parent and 50% outside. So if the height of parent div changes the red still stays on the center vertically.

The way I did was to give bottom: -20px, but if I change the height of the parent then the div won't stay in the center vertically to the bottom border.

Here's the code I came up with.

.parent {
  position: absolute;
  background-color:black;
  width: 200px;
  height: 200px
}

.another-parent {
  position: relative;
  float:right;
  background-color:black;
  width: 200px;
  height: 70px
}

.child {
  position: absolute;
  background-color: red;
  width: 50px;
  height: 50px;
  bottom: -20px;
}
<div class="parent">
  <div class="child">
  </div>
</div>

<div class="another-parent">
  <div class="child">
  </div>
</div>

enter image description here

3 Answers

You can change the height and the child div will stay in place. And the parental diva needs to be given a position: relative.

.parent {
  position: relative;
  background-color:black;
  width: 200px;
  height: 200px
}

.child {
  position: absolute;
    background-color: red;
    width: 50px;
    height: 50px;
    bottom: -25px;
    right: 75px;
}
<div class="parent">
  <div class="child">
  </div>
</div>

Use translateY(50%) combined with bottom:0. This will work for any height including child and parent element:

.parent {
  position: absolute;
  background-color:black;
  width: 200px;
  height: 200px
}

.another-parent {
  position: relative;
  float:right;
  background-color:black;
  width: 200px;
  height: 70px
}

.child {
  position: absolute;
  background-color: red;
  width: 50px;
  height: 50px;
  bottom: 0;
  transform:translateY(50%);
}
<div class="parent">
  <div class="child">
  </div>
</div>

<div class="another-parent">
  <div class="child">
  </div>
</div>

Use percentages for perfect and responsive output.

.parent {
  position: absolute;
  background-color:black;
  width: 200px;
  height: 200px
}

.another-parent {
  position: relative;
  float:right;
  background-color:black;
  width: 200px;
  height: 70px
}

.child {
  position: absolute;
  background-color: red;
  width: 50px;
  bottom: -20px;
left: 35%;
}
<div class="parent">
  <div class="child">
  </div>
</div>

<div class="another-parent">
  <div class="child">
  </div>
</div>

Let me know if it works for you.

Related