Ryan
Ryan

Reputation: 10049

CSS3 DIVs different backgrounds

I am a CSS3 noob, just getting started by using different web examples so please excuse me if this question is silly or too basic (we all have to learn sometime!)

I have a simple example DIV and it's styled like this:

.img1 {
    width:206px;
    height:206px;
    margin-left: auto;
    margin-right: auto;
    background:url(Mom206x206.jpg);

}

Two questions:

1 - is this legal syntax background:url(Mom206x206.jpg) or shouldn't it be with quotes: background:url("Mom206x206.jpg")

2 - How do I use the same class but have different backgrounds? Or will I have to make a different class for every background I want in this style?

Upvotes: 0

Views: 47

Answers (2)

1.- The documentation on URLs and URIs states that:

The format of a URI value is 'url(' followed by optional white space followed by an optional single quote (') or double quote (") character followed by the URI itself, followed by an optional single quote (') or double quote (") character followed by optional white space followed by ')'. The two quote characters must be the same.

So, the following three are valid:

background:url(Mom206x206.jpg)
background:url('Mom206x206.jpg')
background:url("Mom206x206.jpg")

2.- You can use a class to set common properties and individual classes for individual backgrounds:

/* Common styles */
.img {
    width:206px;
    height:206px;
    margin-left: auto;
    margin-right: auto;
}

/* Individual styles */
.img.bg1 { background:url(bg1.jpg); }
.img.bg2 { background:url(bg2.jpg); }
.img.bg3 { background:url(bg3.jpg); }
.img.bg4 { background:url(bg4.jpg); }
.img.bg5 { background:url(bg5.jpg); }

Now you can have your HTML like this:

<div class="img bg1">DIV With background 1</div>
<div class="img bg2">DIV With background 2</div>
<div class="img bg3">DIV With background 3</div>
<div class="img bg4">DIV With background 4</div>
<div class="img bg5">DIV With background 5</div>

Upvotes: 3

Joe
Joe

Reputation: 31

  1. Yes, in quote. For example: background: #00ff00 url('Mom206x206.jpg')
  2. Different class would be cleaner

Upvotes: 3

Related Questions