Placement of background image with h2 tag fill

I want to create a header (h2) with an image in the right pane of the bounding box. I have a layout almost to the right, except that I cannot push the image a little to the right of the bounding box of the element - how would I adjust my CSS so that it displays correctly?

I am trying to do something like this:

[{someHeadLineText}{dynamic space }{image}{5px space}] 

where [] indicates the total available width of my content.

Html:

 <div class="primaryHeader"> <h2>News</h2> </div> 

Css:

 .primaryHeader h2 { background-color: green; /* the header looks like a box */ color: black; background: transparent url(../images/edit.png) no-repeat right center; border: 1px solid red; } 

I place the image to the right of the h2 element and center vertically - but how do I change the position of the background image?

+4
source share
4 answers

I'm afraid I think you can’t. You can use either right or the pixel value as the x-position of the image, but this pixel value will always refer to the left corner of the bounding box. Adding a padding also does not help, it just extends the bounding box.

The only solution I know for this is either adding a shift to the image itself, or using an absolutely positioned element (with a slight offset) that hangs behind the element - but for this you need to know the width and height in advance.

Edit: evil, hacker idea. I don't have time to try this right now, but it should work if h2 is a: block mapping.

Give h2 a position: relative .

Place a div or other element inside h2 with the following:

 position: absolute; left: 0px; top: 0px; right: 5px; /* This is the shift */ bottom: 0px; background-image: url(...); background-position: right center; background-repeat: no-repeat; z-index: -1; /* I don't know whether this will overwrite the h2 content */ 

this can lead to the desired effect, I'm not sure, since I have not tried. An element can overlay h2 other content, in which case you would need to put the rest into a <span> element with position: relative and z-index: 1 .

It really is hacked. Better put the gasket in the image, much cleaner.

+3
source

You can cut the background image and use the image instead.

 <div class="primaryHeader" style="padding-right: 5px;"> <img src="../images/edit.png" alt="" style="float: right;" /> <h2>News</h2> </div> 
0
source

Can you add padding pixels in the image itself?

0
source

You can see CSS3 positioning . It works in all modern browsers (not IE, of course).

0
source

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


All Articles