1

For example, I have a div :

<div>I am a square</div>

Inside style.css :

 div:nth-child(1) {
 height: 200px;
 width: 200px;
 border-radius:0;
 background-color: pink;
 color: #fff;
 text-align: center;
}

The text-align: center property aligns the text in the center of a div, but the text remains on the top inside the square, I want to push the text to the bottom of a square. So it looks like in this diagram. How can I accomplish this without wrapping the text in any sort of tag?

 __________________
 |                |
 |                |
 |                |
 |                |
 |                |
 |_I am a square__|
samkauli
  • 51
  • 1
  • 7
  • Check here: _http://stackoverflow.com/questions/585945/how-to-align-content-of-a-div-to-the-bottom-with-css_ –  Mar 24 '15 at 14:46
  • I looked at that asnwer before. What he does is, header-content is an id that contains text. He gives that id position:absolute; and left and bottom. The #header-content is wrapped inside #header and therefore position: absolute works on #header-content. If I give position absolute to my div, the whole div moves to the bottom of my web page, while the position of a text remains the same. – samkauli Mar 24 '15 at 14:51
  • Check out the second portion of my answer – xyhhx Mar 24 '15 at 15:00

1 Answers1

1

If you really don't want to wrap your text

You can do this by setting the display of the block to be table-cell, and then vertical-align to bottom. This is the only way I can think of to align the text to the bottom of the div without wrapping it in another element. This will cause a slew of other problems with your div placement, though; and you will probably have to wrap the div anyway.

 div {
     height: 200px;
     width: 200px;
     border-radius:0;
     background-color: pink;
     color: #fff;
     text-align: center;
     /* Here is my addition */
     display: table-cell;
     vertical-align: bottom;
 }

enter image description here

JsFiddle example.

If you wrapping your text is an option (AKA the right way)

You really should wrap your text. Aside from semantics, you can get a lot more flexibility in your styling options.

Once you do that, your div can be set to position: relative so that it can act as a container for the child, who will get the position: absolute style. Then you add bottom: 0 and voila! It's glued to the bottom.

This method is preferred as you can still style your div as you'd expect.

HTML:

<div>
    <p>test</p>
</div>
<div>
    <p>test</p>
</div>

CSS:

 div {
     height: 200px;
     width: 200px;
     border-radius:0;
     background-color: pink;
     color: #fff;
     text-align: center;
     margin : 0 3px 3px 0;
     /* Make sure that it contains the child properly */
     position: relative;
 }
 div p {
     position : absolute;
     bottom : 0;
 }

enter image description here

Example

xyhhx
  • 6,384
  • 6
  • 41
  • 64