Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 626
Jules Avatar asked Jan 06 '12 09:01

Jules


People also ask

How can I get h1 tag in center?

text-align: center; on the h1 element and it will automatically center align the h1.

How do I center an IMG?

Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.

How do I change my h1 alignment?

To set the heading alignment in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <h1> to <h6> tag, with the CSS property text-align. HTML5 do not support the align attribute of the heading tag, so the CSS style is used to set alignment.


1 Answers

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/

like image 107
sandeep Avatar answered Oct 13 '22 09:10

sandeep