Background image width

11,176

Solution 1

You can't resize an image set as background of a container. The only way you can resize a image is using a img tag and resizing it with width and height css attributes.

Take a look here may be it helps.

Solution 2

You can use the CSS3 background-size property, for those browsers that support it, then fall back to a compromise solution for older browsers. The compromise solution could be to set a background color to fill up the space around the background image or to use the background-repeat property to "tile" the image.

For example:

#user_avatar {
    ...
    background: url(images/avatars/128.jpg) blue 50% 50% no-repeat;
    background-size: 100px 100px;
}

Solution 3

You could use background-size, however only the most current browsers support it: https://developer.mozilla.org/en/CSS/background-size

Share:
11,176
Cyclone
Author by

Cyclone

Updated on June 07, 2022

Comments

  • Cyclone
    Cyclone about 2 years

    This is my HTML:

    <div id="user-avatar"><img src="/imgs/frame.png" alt=""/></div>
    

    user-avatar class is following:

    #user-avatar {
         width: 100px;
         height: 100px;
         margin: auto;
         position: relative;
         background: url(images/avatars/128.jpg) 50% 50% no-repeat;
    }
    

    Frame:

    #user-avatar img { 
         position: absolute; 
         top: 50%; 
         left: 50%; 
         width: 122px; 
         height: 127px; 
         margin-top: -62px; 
         margin-left: -63px; 
    }
    

    Original user-avatar background image dimensions are 23x25 but I want it to be resized to the 100x100px, and the problem is that whatever I set in the width: xxx attribute it'll not work. The avatar that is behind the frame has everytime his original dimensions.

  • dgvid
    dgvid over 12 years
    Actually, with CSS3-compliant browsers that support it, you can.
  • Cyclone
    Cyclone over 12 years
    Well, is there a way to do it in the img tag for the best compalibility?
  • dgvid
    dgvid over 12 years
    I suppose you could use two img tags. One, the background, would have src images/avatars/128.jpg and the other, the foreground, have src /imgs/frame.png. You would then use absolute positioning to put the two img tags at the correct location relative to #user-avatar, then set the z-index of the foreground img higher than that of the background img.