Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is vertical-align used for in CSS?

Tags:

html

css

I am new to the world of coding as well as CSS and recently came across the property vertical-align. Having read a number of articles on what it is, I am still clueless on what it is for and when do you use it?

My understanding is that it is used for inline elements such as text, images, etc as well as text or other inline elements in a table. They cannot be used for block element such as div, h1, etc.

If my understanding is right, apart from aligning text vertically to say an image or using subscript or superscript, what other purpose does it serve?

like image 520
PeanutsMonkey Avatar asked May 25 '11 22:05

PeanutsMonkey


3 Answers

It's used the vertical align inline elements indeed. Block level elements will ignore this property. So your understanding is right.

This blog gives some background information on vertical-align with some examples. It's mainly used to vertically position an image in a line of text. Or to replace the valign attribute on tablecells.

So it seems you are understanding it quite right. See w3schools for the details on the vertical-align property.

Just to be clear; do not try to use vertical-align to position a blocklevel element like a div. It will not work, as you already mentioned, it's for inline elements like images in a line of text. Using display: table-cell; and vertical-align on an element is a hack, please use other CSS techniques to vertically align stuff in an div whenever possible.

like image 153
Mac_Cain13 Avatar answered Nov 15 '22 09:11

Mac_Cain13


  • It's always worth reading the specs if you want to learn about a specific property:
    http://www.w3.org/TR/CSS21/visudet.html#propdef-vertical-align

  • A common use case is vertical centering (in combination with display: table-cell):

    http://jsfiddle.net/7eTb2/

    div {
        background: #ccc;
        width: 200px;
        height: 300px;
        padding: 5px;
    
        display: table-cell;
        vertical-align: middle
    }
    

    It's somewhat difficult to vertically center without using this technique.

  • Another common use case is when it comes to elements that are inline or inline-block.
    See here for examples of what happens with different vertical-align values: http://www.brunildo.org/test/inline-block.html

  • Another good link to read: http://css-tricks.com/what-is-vertical-align/

However, it's real use is getting me upvotes, see:

  • https://stackoverflow.com/search?tab=votes&q=user%3a405015%20%22vertical-align%3a%20top%22

:)

like image 31
thirtydot Avatar answered Nov 15 '22 10:11

thirtydot


Others have been mostly correct about vertical-align. The reality is that it works, just not how you think. It's for inline elements, not block elements.

In this case, a fiddle is worth a thousand words. :)

http://jsfiddle.net/JJfuj/

like image 42
dtbarne Avatar answered Nov 15 '22 10:11

dtbarne