Frank
Frank

Reputation: 2441

Move div to bottom of parent with other requirements

How can I allign the child div to the bottom of the parent div? The solution needs to keep the hr width full, keep the padding of the parent div working and keep the text aligned to the right.

Why previous answer aren't working:

I will of course look at answers containing positioning or flexbox but I have tried what I know of it without getting to a good solution.

.parent {
  width: 500px;
  height: 250px;
  background-color: gray;
  padding: 10px;
}

.child {
  height: 50px;
  text-align: right;
}
<div class="parent">
  <div class="child">
    <hr>
    <label>I am Batman</label>
  </div>
</div>

Upvotes: 0

Views: 2385

Answers (4)

VXp
VXp

Reputation: 12078

You can do it with the align-self: flex-end:

.parent {
  width: 500px;
  height: 250px;
  background-color: gray;
  padding: 10px;
  display: flex;
}

.child {
  flex: 1; /* mimics "width: 100%" */
  align-self: flex-end; /* affects horizontal alignment, places itself at the bottom of the parent element */
  height: 50px;
  text-align: right;
}
<div class="parent">
  <div class="child">
    <hr>
    <label>I am Batman</label>
  </div>
</div>

Upvotes: 0

patelarpan
patelarpan

Reputation: 8021

You can give margin-top: auto and width: 100% to the child element:

.parent {
  width: 500px;
  height: 250px;
  background-color: gray;
  padding: 10px;
  display: flex;
}

.child {
  height: 50px;
  text-align: right;
  margin-top: auto;
  width: 100%;
}
<div class="parent">
  <div class="child">
    <hr>
    <label>I am Batman</label>
  </div>
</div>

Upvotes: 1

Bhoomi
Bhoomi

Reputation: 537

Since I have used position relative and absolute in parent-child div, it ignores the padding. So you have to set bottom in child div to display it as you want.

.parent {
  width: 500px;
  height: 250px;
  background-color: gray;
  padding: 10px;
  position:relative;
}

.child {
  width:calc(100% - (10px*2));
  height: 50px;
  text-align: right;
  position:absolute;
  bottom:10px;
}
<div class="parent">
  <div class="child">
    <hr>
    <label>I am Batman</label>
  </div>
</div>

Upvotes: 0

Frank
Frank

Reputation: 2441

Add position: relative to the parent and add a few things to the child. This solution works if you are not able to use flexbox on the parent container (though flexbox is a better and easier fix)

Notes:

  • Margin on the child replaces the padding you loose when using position: absolute
  • To fill the width use calc(100% - (10px*2)). This makes the div 100%, then subtracts a 10px margin on each side. This results in a div that fills the area correctly.

.parent {
  width: 1000px;
  height: 500px;
  background-color: gray;
  padding: 10px;
  position: relative;
}

.child {
  height: 50px;
  background-color: orange;
  text-align: right;
  position: absolute;
  bottom: 0px;
  right: 0px;
  margin: 10px;
  width: calc(100% - (10px*2));
}

Upvotes: 0

Related Questions