Freigeben über


CSS tip: Extract what's common (define class in multiple parts)

There are often cases where similar (but not exactly the same) CSS styles are defined. Avoid the redundancy by grouping the common styles and creating a second style for the difference.

For example, here are two classes that define a menu item when it is not selected and selected. They look the same except the menu item is underlined when selected.
.menuItem
{
    color: black;
    background: white;
    border: none;
    margin-left: 10px;
    margin-top: 5px;
}

.menuItemSelected
{
    color: black;
    background: white;
    border: none;
    margin-left: 10px;
    margin-top: 5px;
    text-decoration: underline;
}

Instead, the items can be grouped differently by combining the common elements and then also defining an extra style for .menuItemSelected. There is also the added benefit that the corresponding menuItem and menuItemSelected styles will always be in sync and look the same because both selectors use the same class.

.menuItem,
.menuItemSelected
{
    color: black;
    background: white;
    border: none;
    margin-left: 10px;
    margin-top: 5px;
}

.menuItemSelected
{
    text-decoration: underline;
}