Daily Archive for July 28th, 2009

CSS Indentation Trick

While reading a Wordpress stylesheet recently, I stumbled upon an interesting way to nest CSS selectors and their associated rules. To illustrate, here’s a listamatic example of list stylesheet:

ul#navlist
{
margin: 0 0 0 30px;
padding: 0;
width: 12.5%;
}

#navlist li
{
list-style-type: none;
background-color: #191970;
color: #daa520;
border: .2em solid #daa520;
font-weight: 600;
text-align: center;
padding: .3em;
margin-bottom: .1em;
}

#navlist li a
{
color: #daa520;
text-decoration: none;
display: block;
}

#navlist li a:hover
{
background-color: #faebd7;
color: #191970;
}

And here’s the reindented version:

ul#navlist {
  margin: 0 0 0 30px;
  padding: 0;
  width: 12.5%;
}
  #navlist li {
    list-style-type: none;
    background-color: #191970;
    color: #daa520;
    border: .2em solid #daa520;
    font-weight: 600;
    text-align: center;
    padding: .3em;
    margin-bottom: .1em;
  }
    #navlist li a {
      color: #daa520;
      text-decoration: none;
      display: block;
    }
    #navlist li a:hover {
      background-color: #faebd7;
      color: #191970;
    }

The idea is to combine the common prefixes in selectors as branches of a tree, and then indent each node of the tree by its depth in the tree (and place it right below its parent node or elder sibling). From what I gather, the position of the braces varies depending on personal styles, but the basic indentation rules apply as such.