Search code examples
htmlcssalignment

Align part of an image


I would like to use a very wide image on my website. There is one main item on the image, the rest is sort of a background. But I would like this main item to be aligned at all times, while the image should show the more or less background depending on how wide the window size is...

I've tried to make it clear in an image:
enter image description here

So, the red border is the whole image (it had a width of 4000px) but it has only one main item on it. In my case a photo of a girl. The background (everything inside the red border besides the green border) is filled with some flowers. What I want is to be the girl (green border) to be aligned in the middle by all means. And depending on the size of the window, the flowers should be more or less visible (but without a scrollingbar).

But I don't have any idea how to do this... Anyone with advice?

enter image description here


Solution

  • If it's a single decorative image, then you can use:

    background-image: url(whole.jpg) 50% 50% no-repeat
    

    Adjust the first percentage if your interesting part of the image is not exactly in the center.

    If you'd like to use a separate <img> for the girl, and separate image for the flowers, then use one of the usual vertical-CSS-centering hacks for the <img> e.g.

    #container {position:relative; overflow:hidden}
    #container img {position:absolute; top:50%; left:50%; 
        margin-top:-half-of-image-in-px; margin-left:-half-of-the-image-in-px;}
    

    and the former style for the background.

    If you want to be cutting-edge, you can use CSS3 object-fit property.