recneps recneps - 7 months ago 8
HTML Question

Understanding CSS Grouping/ Nesting

I know similar questions to this have been asked a bunch of times but I could not find an answer for my specific one. If I have a bunch of CSS selectors that are very similar but are only just different how can I nest or group them.

Here is what I am trying to do.

#cell-left {
background-color:#DDDDDD;
border:2px solid;
height:400px;
margin:20px 10px 0px 32px;
padding: 40px 15px 15px 15px;
text-align:center;
}
#cell-center {
background-color:#DDDDDD;
border:2px solid;
height:400px;
margin:20px 10px 0px 10px;
padding: 40px 15px 15px 15px;
text-align:center;
}
#cell-right {
background-color:#DDDDDD;
border:2px solid;
height:400px;
margin:20px 32px 0px 20px;
padding: 40px 15px 15px 15px;
text-align:center;
}
#row {
width:100%;
margin-top:0px;
}


As you can see all the cells are very common to each other they just have slightly different margins. I know there is a way to do all the cells the exact same then add a .right, .center and .left with just margin in the CSS and cut down on a lot of code.

Thanks in advance for the answer.

Answer

Create a cell class which contains the duplicate properties and add it to each of the DOM elements.

CSS

.cell{
   background-color:#DDDDDD; 
   border:2px solid;
   height:400px;
   padding: 40px 15px 15px 15px;
   text-align:center; 
}

#cell-left{
    margin:20px 10px 0px 32px; 
}

#cell-center {
    margin:20px 10px 0px 10px; 
}

#cell-right {
    margin:20px 32px 0px 20px;
 }

HTML

<div id="cell-left" class="cell">Something</div>
<div id="cell-right" class="cell">Something</div>
<div id="cell-center" class="cell">Something</div>

Example: http://jsfiddle.net/hKLMj/

Comments