简体   繁体   中英

get background image or text to fill width, not repeat, but not stretch vertically

Just as the title says. How can I get a background image, or even text to fill width wise, not stretch/squash vertically, and just show up once? I can't seem to figure this out. Thank you.

Edit: I also want the height to scale with the width of the picture proportionally, so it will not be skewed but scaled with the width.

If you only want the background img to fill the width without taking into account the height you can do:

.element-with-back-img{
    background-repeat: no-repeat;
    background-size: 100%;
}

but with this the img doesn't fill the height of element-with-back-img because the height will set to "auto"

By doing this:

.element-with-back-img{
    background-repeat: no-repeat;
    background-size: 100% 100%;
}

the img fills the height but if element-with-back-img has different proportions than those from the img, this one will change its proportions to fill the element-with-back-img

I recommend u to:

.element-with-back-img{
    background-repeat: no-repeat;
    background-size: cover;
}

this scale the background image to be as large as possible so that the background area is completely covered by the background image. Some parts of the background image may not be in view within the background positioning area

I hope this could help u

 .test { background-image: url(http://placekitten.com/1000/750); background-size: 100%; background-repeat: no-repeat; background-color: lightblue; height: 150px; display: inline-block; } #test1 { width: 200px; } #test2 { width: 100px; } #test3 { width: 300px; } .test:hover { background-position: center center; } 
 <div class="test" id="test1"></div> <div class="test" id="test2"></div> <div class="test" id="test3"></div> 

Use css for the body:

body {background-repeat: no-repeat;
      background-size: 100%;}

To fill width-wise, use 'background-size'. That allows you to enter two parameters - width and height, in that order. Use '100%' to fill the width, then a fixed value for the height (assuming you know what the height of your image is).

Eg if your background image is 500px tall, then:

{
    background-size:100% 500px;
    background-repeat: no-repeat;
}

You can experiment for yourself here .

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