How to place the center next to a floating element and relative to its containing element?

I have a markup that looks like this:

<div> <h1 style="text-align:center;" >Heading 1</h1> <img style="float:left;" src="logo.gif"/> <h1 style="text-align:center;" >Heading 2</h1> </div> <div> Content goes here </div> 

The problem is that heading 2 is centered relative to the rest of the space after the image, and not for the entire div, so it does not center on the page.

If I remove img from the stream with the position: absolute, it does not click on the content and instead overlaps it.

+7
css center css-float
source share
4 answers

I solved it with trial and error. I don’t know why, but in my testing it only works if the width is set between 12 and 80%.

So, it seems that "h1" is a block element, and text-align does not center the elements of the block, it only centers in-line elements inside it, which explains the behavior of the "centered off-center". So, it turns out that the answer is the same answer to the question "how do you center a block element?"

 <div> <h1 style="text-align:center;">Heading 1</h1> <img style="float:left;" src="logo.gif"/> <h1 style=" text-align:center; margin-left:auto; margin-right:auto; width:50%; ">Heading 2</h1> </div> <div style="clear:both;"> Content goes here </div> 
+1
source share

One way is to add the correct complement to the div with the logo size:

 <div style="padding-right: 50px;"> <img style="float:left;" src="logo.gif"/> <h1 style="text-align:center;" >Heading</h1> </div> <div> Content goes here </div> 

Another way is to remove the header from the stream. This only works if the height of the logo is greater than the height of the title. Also beware that the image and title may overlap.

  <h1 style="position: absolute; width: 100%; text-align:center;"> Heading </h1> <img style="float:left;" src="logo.gif"/> <div style="clear:both;"> Content goes here </div> 
+1
source share

If you really use the logo, you can try this solution:

 <div> <img style="float:left;" src="logo.jpg"/> <h1 style="text-align:center; position:relative; left:-100px;" >Heading</h1> </div> 

where -100px replace half your image width.

change

An idea with an absolute position from a small green answer works. Check this:

 <div style="position:relative;"> <img style="float:left; position:absolute;" src="logo.jpg"/> <h1 style="text-align:center;" >Heading</h1> </div> 
0
source share

This is the simplest solution:

<h2 style="text-align:center;text-indent:-*px">Heading 2</h2>

  • = logo width
0
source share

All Articles