简体   繁体   中英

How to make background image for a div responsive?

How could I use img-responsive of bootstrap to a div as follows:

<div class="fill" style="background-image:url
                                            ('./images/abc.jpg');">
</div>

While I am trying to add img-responsive class inside the div along fill it doesn't work. How could I make the background image for the above div responsive?

div {
    background-image:url('./images/abc.jpg');
    background-repeat:no-repeat;
    background-size:contain;
}
  1. If the background-size property is set to "contain", the background image will scale, and try to fit the content area. However, the image will keep its aspect ratio (the proportional relationship between the image's width and height):

      div { width: 100%; height: 400px; background-image: url('img_flowers.jpg'); background-repeat: no-repeat; background-size: contain; border: 1px solid red; } 
  2. If the background-size property is set to "100% 100%", the background image will stretch to cover the entire content area:

      div { width: 100%; height: 400px; background-image: url('img_flowers.jpg'); background-size: 100% 100%; border: 1px solid red; } 
  3. If the background-size property is set to "cover", the background image will scale to cover the entire content area. Notice that the "cover" value keeps the aspect ratio, and some part of the background image may be clipped:

      div { width: 100%; height: 400px; background-image: url('img_flowers.jpg'); background-size: cover; border: 1px solid red; } 

Look, there is a nice technique using background-size property

.fill {
    background: url(path/to/img.jpg) center center no-repeat;
    -webkit-background-size: cover;
    background-size: cover;
}

This rule will make your background image cover all container space and adjust when scaling the window.

Use background-size property to the value of 100% auto to achieve what you are looking for.

For instance,

.fill{
   background-size:100% auto;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM