sourcingsynergy
sourcingsynergy

Reputation: 605

How to Set Up a Responsive Background-Image with CSS

Have two div-classes: a bar that nests a menu

background-image isn't properly scaled or responsive when placed in bar class, and isn't appearing when placed in the menu class, where it seems fitting to style responsively.

Also, the image is png, but gets rendered with white-space in the clear-space … why might this be?

Testing both as inline styles now, but, in an external style sheet nested in a 'css' folder, how can the image be pointed to in an 'img' folder adjacent the path of the 'css' folder?

For Responsiveness…the background-image should scale with the Browser height/width, as appropriate..

Current CSS:

.bar {
  position: static;
  bottom: 0;
  height: 10%;
  width: 100%;
  display: block;
  margin: 0 auto;
  text-align: center;
}

.menu {
  display: inline-block;
  background-image: url("img/menu-bar.png");
}

Upvotes: 0

Views: 9475

Answers (1)

nullability
nullability

Reputation: 10675

You are asking several questions here. So, in order:

By default, background-image will be repeated at its actual size. If you want it to scale, you should set the background-size and probably disable background-repeat. To have the image scale to the size of the container, you can set background-size: 100% 100%; or you could use background-size: cover to fill the container on the smaller dimension and clip off the rest. The other option is to use background-size: contain to avoid clipping the image.

As to the path issue, paths are always relative to the CSS file. So if, as you say, the stylesheet is in a css folder adjacent to the img folder, you would just set the path relative to the css folder.

You final CSS might look something like this:

.menu {
  display: inline-block;
  background-image: url(../img/menu-bar.png);
  background-size: cover;
  background-color: transparent;
  background-repeat: no-repeat;
}

Note that I removed the quotes as they are not necessary.

Finally, if your transparency isn't working then there must be something wrong with the image file itself. CSS has nothing to do with PNG transparency. Make sure your graphics editor is saving the PNG with the appropriate transparency.

Upvotes: 3

Related Questions