Search code examples
csshtmlcenter

img in div float left with text centered vertically and horizontally


I feel like this should be (and probably is) answered somewhere, but either that's not the case, I'm not searching the right way, or it's some closely guarded national secret, because I cannot find an answer that works. Specifically, I cannot find an answer that accommodates the image on the left side of my div.

What I'm trying to effect is for the text to be centered horizontally with regards to the entire screen and vertically within the 'header' div. I don't want to use my logo as a background, because I'm using it as a home anchor. I have tried to using 'display: table-cell' and 'vertical-align: middle' to disastrous result. Please, any advice/help/link is appreciated.

CSS:

#header{
    width: 85%;
    min-width: 500px;
    text-align: center;
    margin-left: auto;
    margin-right: auto;
    overflow: hidden;
    background-color: #fff;
    border-bottom-width: 10px;
    border-bottom-style: double;
    border-bottom-color: #000;
}

#title{
    width: 85%;
    margin-left: auto;
    margin-right: auto;
    position: absolute;
    display: table-cell;
    vertical-align: middle;
}

#logo{
    float: left;
    padding-right: 1em;
    width: 150px;
}

HTML:

<div id="header">

      <a href="."><img id="logo" src="../images/logo.jpg" alt="Widget News" /></a>
    <span id="title"><h1>Site Title</h1></span>
      </div>

Also, I'm completely new to using CSS (and pretty useless with xhtml/html5). I'm working on my current project as a means to familiarize myself with CSS/PHP/HTML/JScript, and so far, the CSS/HTML is the only part that I'm having problems with. Any pointers to a good beginner's, but not remedial/'for dummies', guide would also be appreciated.


Solution

  • I'd recommend making your logo absolutely positioned. That will take it out of the flow of the html elements (like a background image does) while keeping it still clickable.

    #logo {
    position: absolute;
    top: 5px;
    left: 10px;
    width: 150px;
    }
    

    That will make it easier to center your title. Here's the full example with a few adjustments to your code:

    http://jsfiddle.net/gqvUv/

    Your "text-align: center;" keeps everything centered horizontally, and adjusting the line-height of your h1 will work to center it vertically, as long as the title is just one line.

    It's easy to get confused by relative and absolute positioning, but this tutorial makes it clear: http://www.barelyfitz.com/screencast/html-training/css/positioning/

    Finally, this is my go-to article on centering things with CSS: http://designshack.net/articles/css/how-to-center-anything-with-css/