Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ashleygwilliams/5114166 to your computer and use it in GitHub Desktop.
Save ashleygwilliams/5114166 to your computer and use it in GitHub Desktop.
GOAL: use selector abstraction to reduce redundancy in our CSS.
PROMPT: Refactor this code.
HTML:
<a href="learn_more.html class="learn_more">Learn More</a>
<button href="contact.html" class="contact">Contact Us</button>
CSS:
.learn_more {
border: 1px solid #000;
background-color: red;
color: white;
text-transform: uppercase;
}
.contact {
border: 1px solid #000;
background-color: blue;
color: white;
text-transform: uppercase;
}
DISCUSSION:
This code is not DRY for several reasons.
1. the border, color, and text-transform declarations are repeated
2. both of these elements are very similar, yet the HTML doesn't reflect that.
we should make the markup more semantic.
ANSWER(S):
1. Combine selectors (OK)
.learn_more, .contact {
border: 1px solid #000;
background-color: red;
color: white;
text-transform: uppercase;
}
.contact {
background-color: blue;
}
2. Use selector abstraction to create a new class (BETTER)
<a href="learn_more.html class="btn">Learn More</a>
<button href="contact.html" class="btn contact">Contact Us</button>
.btn {
border: 1px solid #000;
background-color: red;
color: white;
text-transform: uppercase;
}
.contact {
background-color: blue;
}
3. Use selector abstraction to create a new class, and create new classes for each option (BEST)
<a href="learn_more.html class="btn btn-red">Learn More</a>
<button href="contact.html" class="btn btn-blue">Contact Us</button>
.btn {
border: 1px solid #000;
color: white;
text-transform: uppercase;
}
.btn-blue {
background-color: blue;
}
.btn-red {
background-color: red;
}
CONCLUSION
Classes don't need to match the content so much as they need to match the role the content plays.
Use abstraction to keep you classes reusable. When designing classes, think about building capacity.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment