背景图像: 如果图像很小,如何填充整个 div,反之亦然

我有三个问题:

  1. 当我试图在小尺寸的 div 中使用背景图像时,div 只显示图像的一部分。如何显示图像的全部或特定部分?

  2. 我有一个较小的图像,我想用在一个较大的 div。但不想使用重复函数。

  3. 在 CSS 中有什么方法可以操纵图像的不透明度吗?

322468 次浏览

Resize the image to fit the div size.
With CSS3 you can do this:

/* with CSS 3 */
#yourdiv {
background: url('bgimage.jpg') no-repeat;
background-size: 100%;
}

How Do you Stretch a Background Image in a Web Page:

About opacity

#yourdiv {
opacity: 0.4;
filter: alpha(opacity=40); /* For IE8 and earlier */
}

Or look at CSS Image Opacity / Transparency

  1. I agree with yossi's example, stretch the image to fit the div but in a slightly different way (without background-image as this is a little inflexible in css 2.1). Show full image:

    <div id="yourdiv">
    <img id="theimage" src="image.jpg" alt="" />
    </div>
    
    
    #yourdiv img {
    width:100%;
    /*height will be automatic to remain aspect ratio*/
    }
    
  2. Show part of the image using background-position:

    #yourdiv
    {
    background-image: url(image.jpg);
    background-repeat: no-repeat;
    background-position: 10px 25px;
    }
    
  3. Same as the first part of (1) the image will scale to the div so bigger or smaller will both work

  4. Same as yossi's.

Rather than giving background-size:100%;
We can give background-size:contain;
Check out this for different options avaliable: http://www.css3.info/preview/background-size/

To automatically enlarge the image and cover the entire div section without leaving any part of it unfilled, use:

background-size: cover;

This will work like a charm.

background-image:url("http://assets.toptal.io/uploads/blog/category/logo/4/php.png");
background-repeat: no-repeat;
background-size: contain;

Try below code segment, I've tried it myself before :

#your-div {
background: url("your-image-link") no-repeat;
background-size: cover;
background-clip: border-box;
}

This worked perfectly for me

background-repeat: no-repeat;
background-size: 100% 100%;