23

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;
}
ErraticFox
  • 1,363
  • 1
  • 18
  • 30
  • ErraticFox, a simular Q with a bounty for a cross browser solution, (IE<7) was asked and answered here: http://stackoverflow.com/questions/7273338/how-to-vertically-align-an-image-inside-div – Wayne Jan 12 '14 at 03:46
  • +1 for @Wayne's link. Never seen that approach, but man is it cool. – knrz Jan 12 '14 at 03:48
  • @Wayne I tried that, I couldn't get it to work for myself. – ErraticFox Jan 12 '14 at 04:02
  • Erratic place the .helper as a sibling of logo. display:inline-block both logo and .helper. CSS the helper height:100%. Height of img is still unknown. vertical-align: middle on both elements logo and helper. Logo div height will expand to img height, and center will align to the center of helper. Yes its a bit complicated. – Wayne Jan 12 '14 at 04:07
  • @Wayne yes but it seems it would be impossible to add text that is vertically centered with the image with that method. It aslo seems impossible to vertically center text with the method gave me also, at least to my knowledge. :\ – ErraticFox Jan 12 '14 at 04:35
  • text would need to be CSS as display:inline-block or CSS as line-height:100%; placing the text in the .helper with line-height:100% makes the most sence. – Wayne Jan 12 '14 at 04:44

1 Answers1

3

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;
}
knrz
  • 1,801
  • 1
  • 12
  • 15