Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS background image for DIV not working with auto

Tags:

html

css

Does background-image not work with percentage div sizes? The images only show up if I hardcode width and height in the .contrast class. Images don't show up if width and height are percentages. Any insight?

CSS:

.parent{
    width=1000px;
}
img.contrast{
    width:400px;
    height:100px;
    background-image: url(http://www.jpl.nasa.gov/spaceimages/images/mediumsize/PIA17011_ip.jpg);
}

HTML:

<div class="parent">
    <img class="contrast"/>
    <img class="contrast"/>
    <img class="contrast"/>
</div>

JsFiddle

Edit1: So .contrast cannot inherit the size of the parent division? If I had 3 divisions within a parent division set to 25% width, it can't access the parent's width?

like image 287
user3808357 Avatar asked Mar 04 '26 05:03

user3808357


1 Answers

Unless you use it as SRC, the container has no way to know wich size is your background.

That been said, you can just use divs for that purpose, and play with the background-size, background-position properties to get the desired effect (i.e. make the background fit the div size). What you cannot do is to make the div "inherit" the size from its background property.

Take a look at this fiddle I made from yours: http://jsfiddle.net/amenadiel/x9a56/2/

img.contrast{
    width:450px;
    height:100px;
    background-image: url(http://www.jpl.nasa.gov/spaceimages/images/mediumsize/PIA17011_ip.jpg);
}

img.contrast2{
    width:50%;
    height:100px;
    background-image: url(http://www.jpl.nasa.gov/spaceimages/images/mediumsize/PIA17011_ip.jpg);
}

img.contrast3{
    width:20em;
    height:100px;
    background-image: url(http://www.jpl.nasa.gov/spaceimages/images/mediumsize/PIA17011_ip.jpg);
}

You can have the divs (or imgs) take absolute widths, or widths relative to the parent, or widths relative to the window. That''s not a problem, because the container has a width from which you can relate. But it wou fail to provide a height for each one, they won't have any.

In turn, the container div expands to fit the total height of its children elements. But, as an alternative workaround, If you provide a fixed height for the container, then you can assign relative heights to the children img.

TL/DR

use img with src attribute to guess size from the image url, or pick your favorite workaround

like image 105
ffflabs Avatar answered Mar 06 '26 20:03

ffflabs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!