0

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.

naspinski
  • 34,020
  • 36
  • 111
  • 167

3 Answers3

2

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>
vals
  • 61,425
  • 11
  • 89
  • 138
Yandy_Viera
  • 4,320
  • 4
  • 21
  • 42
  • Added snippet of the option that (in my opinion) best fits the OP question. good answer ! – vals Jun 03 '15 at 16:01
  • I added a bit to my description - I want it to fill the page (dynamic width) on the x-axis, and scale proportionally on the y-axis without distorting the image. I am not sure if these cover it or not and will be trying it out later - either way, thank you! – naspinski Jun 03 '15 at 20:38
0

Use css for the body:

body {background-repeat: no-repeat;
      background-size: 100%;}
JRQ
  • 545
  • 4
  • 17
0

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).

E.g. if your background image is 500px tall, then:

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

You can experiment for yourself here.

Mike K
  • 486
  • 3
  • 7