Search code examples
htmlcssimagecenteralignment

How can I center my <h1> when there is an <img /> next to it?


I have a problem creating a decent header in CSS. What I want is a <h1> header that aligns its content in the center of its parent <div>. Sometimes though there might be an additional logo displayed as a regular <img /> which should be aligned to the left.

This is my example code:

<div class="container">
    <div class="logo">
        <img src="http://www.oldfirestation.co.uk/logo_brand_example_86.jpg" />
        <h1>Not center?</h1>
    </div>
    <div class="more">
        This is the center
    </div>
</div>

And my CSS:

body {
    background-color: #161616;
}

div.container {
    background-color: #fff;
    width: 70%;
    margin: auto;
}

div.logo img {
     width: 200px;   
    float: left;
}

h1 {
    text-align: center;
    font-size: 1.4em;
    margin: 0px auto;
    padding: 0px 0px 5px 0px;  
    width: 50%;
}

div.more {
    text-align: center;
    margin-top: 50px;
    clear: left;
}

The problem is that when I show an <img />, my <h1> text is NOT centered. If I remove this <img /> it is... How can I fix it??

I have made an example on JSFiddle here: http://jsfiddle.net/8B9ZF/


Solution

  • You do like this:

    div.logo img {
         width: 200px;   
        vertical-align:middle;
    }
    
    h1 {
        text-align: center;
        font-size: 1.4em;
        margin: 0px auto;
        padding: 0px 0px 5px 0px;  
        width: 50%;
        display:inline-block;
    }
    

    http://jsfiddle.net/8B9ZF/8/

    May be you can change your mark-up

    http://jsfiddle.net/8B9ZF/24/