Search code examples
htmlcssbackgroundbackground-size

How to assign CSS background image properties mixing classes and ids


I am wondering if any of you have any tricks to make this happen, or if I'm completely overthinking this.

I have MANY images being used and the most efficient (and easiest) way to make these images show up is to use the CSS background:url("link"); property where link is the proper link to my image file. This prevents cluttering of my html files as well.

The issue is that the above code is found in over 50 different ids, each pointing to a different image and I need to resize the images, however I would REALLY like to not have to put the following code under each and every id.

background-size:180px 239px;
background-repeat:no-repeat;

To put this simply: I have CSS that looks something like this...

My "ID"s

#image1
{
    background:url("../Images/image1.png");
}

#image2
{
    background:url("../Images/image2.png");
}

#image3
{
    background:url("../Images/image3.png");
}

My class

.myClass
{
    width:180px;
    height:239px;
    background-size:180px 239px;
    background-repeat:no-repeat;
}

Note that by entering this code all will seem normal, however if you change the values in background-size (say to 100px 239px you will notice the issue that I am experiencing)


And a typical use of this in html would be as the following:

<div id="image1" class="myClass"></div>

A jsfiddle of this issue can be found here: jsfiddle

The anticipated result is shown under the text in the fiddle.

How would I go about coding this so that it remains clean?

I would like to note that I am trying to keep my CSS and JS separate. I am looking for a purely CSS way for coding this. I need control of all the id's background-properties from one single location.

Any help with this is greatly appreciated, thank you.


Solution

  • Change background to background-image and it will work :)

    #image1
    {
        background-image:url("http://upload.wikimedia.org/wikipedia/commons/thumb/3/3b/Bolognese_Image.jpg/180px-Bolognese_Image.jpg");
    }
    
    #image2
    {
        background-image:url("http://www.phy.duke.edu/~kolena/Recommended.gif");
    }
    
    .myClass
    {
        width:180px;
        height:239px;
        background-size:100px 239px;
        background-repeat:no-repeat;
        border:2px solid red;
    }
    
    /*------------------------------------*/
    
    
    #thisIsWhatIWantItToLookLike
    {
        background-image:url("http://www.senoja.nl/images/mainecoons/galleryxamina/xamina1.jpg");
        background-size:100px 239px;
        background-repeat:no-repeat;
    }
    
    .mySadClass
    {
        width:180px;
        height:239px;
        border:2px solid blue;
    }
    <div id="image1" class="myClass"></div>
    <div id="image2" class="myClass"></div>
    <p>This above images should show up like the one below does, squished</p>
    <div id="thisIsWhatIWantItToLookLike" class="mySadClass"></div>