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

I have a problem creating a decent title in CSS. What I want is a <h1> header that aligns its contents in the center of its parent <div> . Sometimes, although there may be an additional logo displayed as a regular <img /> , which should be aligned with the left .

This is my sample 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 <img /> , the text <h1> NOT centered. If I remove this <img /> , this ... How can I fix it ??

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

+6
source share
3 answers

Do you like it:

 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/

Perhaps you can change your markup

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

+4
source

If you make the image absolutely positioned at 0.0 instead of floating, it will not push H1 out of the center. But then you endanger the image that overlaps the text if the image is too large or the container is too small. To counter this, you probably want to add some padding left / right of the container

0
source

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

it should always work, as far as I know! basically it just adds overflow hiding, which makes h1 aware of the space that the floating element occupies, so it takes up the remaining area!

 body { background-color: #161616; } div.container { background-color: #fff; width: 70%; margin: auto; } div.logo{ overflow:hidden } div.logo img { width: 200px; float: left; } h1 { text-align: center; font-size: 1.4em; padding: 0px 0px 5px 0px; } div.more { text-align: center; margin-top: 50px; clear: left; } 
0
source

Source: https://habr.com/ru/post/905286/


All Articles