Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical aligning never ever works

Tags:

html

css

Yes, obviously I'm doing it wrong. Why can't it be as easy as horizontally aligning stuff? I sit and my work is halted for hours on end trying to look up how to vertically align in the middle, so I don't have to bug you guys with my stupid most-likely really easy to you question.

Display Block or Table-Cell, everything I read never works. I thought "maybe if I horizontally align my img with .divID img and then vertically align the div itself" sadly, I wish that'd work. But even when I did try centering the div vertically in the middle, it messed up the image centering and didn't even work.

TL;DR: I hate trying to vertically align stuff so much.

I'm trying to get my header image centered vertically and horizontally. This my code I'm working off.

HTML

<div id="wrapper">
    <div id="header">
        <div id="logo">
            <img src="http://i.imgur.com/d0umnxt.png" />
        </div>
    </div>
</div>

CSS

body {
    margin: 0px;
}
#header {
    width: 100%;
    height: 100px;
    background-color: #151B1F;
}
#logo {
    display: block;
    margin: auto;
}
like image 834
ErraticFox Avatar asked Jan 12 '14 03:01

ErraticFox


People also ask

Is vertical-align deprecated?

Deprecated as an attribute Occasionally you will see “valign” used on table cells to accomplish vertical alignment. e.g. <td valign=top> . It should be noted that this attribute is deprecated and should not be used.

How Vertical-Align works?

The vertical-align property in CSS controls how elements set next to each other on a line are lined up. In order for this to work, the elements need to be set along a baseline. As in, inline (e.g. <span> , <img> ) or inline-block (e.g. as set by the display property) elements.

Does the vertical-align property act the same way for all elements?

The vertical-align property works only on inline or inline-block elements and table cells and when not used on a table cell, it will affect the alignment of the element itself, not the element's contents.

When can I use vertical-align?

The vertical-align property can be used in two contexts: To vertically align an inline element's box inside its containing line box. For example, it could be used to vertically position an image in a line of text. To vertically align the content of a cell in a table.


1 Answers

I hate table and table-cell just as much as the next guy, but when you know the height of the parent element (#header in your case), things become really easy.

Here's a working fiddle.

You just need to add the following styles to your CSS:

#header {
    display: table;
}
#logo {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
like image 187
knrz Avatar answered Oct 10 '22 10:10

knrz