83

I tried to align my text to the bottom of a div from other posts and answers in Stack Overflow I learned to handle this with different CSS properties. But I can't get it done. Basically my HTML code is like this:

<div style='height:200px; float:left; border:1px solid #ff0000; position:relative;'>
  <span style='position:absolute; bottom:0px;'>A Text</span>
</div>

The effect is that in FF I just get vertical line (the div in a collapsed way) and the text is written next to it. How can I prevent the div collapsing but having the width fitting to the text?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
parascus
  • 1,079
  • 1
  • 10
  • 14

2 Answers2

163

Flex Solution

It is perfectly fine if you want to go with the display: table-cell solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;. flex is something which has a decent support.

.wrap {
  height: 200px;
  width: 200px;
  border: 1px solid #aaa;
  margin: 10px;
  display: flex;
}

.wrap span {
  align-self: flex-end;
}
<div class="wrap">
  <span>Align me to the bottom</span>
</div>

In the above example, we first set the parent element to display: flex; and later, we use align-self to flex-end. This helps you push the item to the end of the flex parent.


Old Solution (Valid if you are not willing to use flex)

If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell; with vertical-align: bottom; is enough

div {
  display: table-cell;
  vertical-align: bottom;
  border: 1px solid #f00;
  height: 100px;
  width: 100px;
}
<div>Hello</div>

(Or JSFiddle)

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
  • 3
    Cool!!! That's it! It works also without the width-property which I have to omit for haveing the div fitting to the content. Thanks! – parascus Jun 15 '13 at 11:59
  • 1
    @parascus It saves you so many properties which you were trying with.. and you welcome :) – Mr. Alien Jun 15 '13 at 12:00
  • 1
    @blackhawk why would you use this solution if your parent wrapper is set to `inline-block`? This is specifically for people who can use `display: table-cell;` – Mr. Alien Jun 10 '16 at 03:08
  • Brilliant solution! – f055 Oct 25 '17 at 15:21
57

You now can do this with Flexbox justify-content: flex-end now:

div {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
  width: 150px;
  height: 150px;
  border: solid 1px red;
}
  
<div>
  Something to align
</div>

Consult your Caniuse to see if Flexbox is right for you.

Zequez
  • 3,399
  • 2
  • 31
  • 42