3

I'm new to web development in general and I am stil just a novice in HTML and CSS.

I am currently trying to minimize the number of declarations in my stylesheet to clean it up, but I have come across something I need help with.

Anyway, here is the code I'm asking about:

#div1,
#div2,
#div3 {
    width: 100px; height: 100px;
    border: 1px solid #f00; 
    background-color: #0f0; 
    float: left; margin: auto 5px auto;
    position: relative; left: 10px; top: 10px;
}

Here, each div has a green background color. What I'm trying to do is set a different color for each div in a single declaration.

Is this possible?

Thanks. Appreciate any and all help.

NoviceGuy
  • 33
  • 2
  • 2
    If clean organized stylesheets is your thing, I would suggest checking out [SASS.] (http://sass-lang.com/) It is designed to minimize the number of declarations in your code and support scalability. – Chairs Dec 19 '16 at 20:00

2 Answers2

2

The cleanest way to style these elements would be to put a common class on them, and only style the individual divs for their differences (the color).

.box {
  width: 100px;
  height: 100px;
  border: 1px solid #f00;
  float: left;
  margin: auto 5px auto;
  position: relative;
  left: 10px;
  top: 10px;
}
#div1 {
  background-color: #0f0;
}
#div2 {
  background-color: #0ff;
}
#div3 {
  background-color: #ff0;
}
<div class="box" id="div1"></div>
<div class="box" id="div2"></div>
<div class="box" id="div3"></div>
Jon Uleis
  • 17,693
  • 2
  • 33
  • 42
0

in css code

#box{
 width: 100px;
  height: 100px;
  border: 1px solid #f00;
  float: left;
  margin: auto 5px auto;
  position: relative;
  left: 10px;
  top: 10px;
}

in html code

<div id="box" style="background:green"> </div>
<div id="box" style="background:red"> </div>
<div id="box" style="background:blue"> </div>
Martian
  • 99
  • 1
  • 11
  • Having more than one element with the same ID is not valid HTML. – Jon Uleis Dec 19 '16 at 20:41
  • if all elements are div is a valid, ID don't works with different tags – Martian Dec 19 '16 at 20:52
  • 1
    Not sure I understand. IDs are not to be repeated on a page, you can only have one `#box` if you want valid HTML. Read more: http://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page – Jon Uleis Dec 19 '16 at 20:54
  • i think this is a valid ! but if you don't like it, change it to class, what's a problem? :)) – Martian Dec 19 '16 at 20:56
  • It's not a matter of opinion - class would be valid, but ID is not. Just trying to point out an error. Here's the relevant W3C spec page: https://www.w3.org/TR/WCAG20-TECHS/H93.html – Jon Uleis Dec 19 '16 at 20:57