Consistent overlays with pseudo-elements

#css #ux #web

Last week I wrote about extending hit areas in CSS; just one handy application of pseudo-elements. Another convenient use is defining consistent overlays.

Consider a button, like the following:

button {
    display: block;
    position: relative;
    background: #226be4 linear-gradient(top, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0));
    border-radius: 2px;
    line-height: 44px;
    color: #fff;
    text-align: center;
    width: 320px;
    height: 44px;

To define the button's :active state, one might change its colour, dim the type or reduce the gradient. This approach is fine, but as soon as you introduce alternate button styles with different colours, or apply the same logic to other UI components, you need to define the pseudo-classes for those too. Then, if you want to tweak any of the attributes further down the track, you must also change those of the :active states.

Enter the pseudo-element:

button::after {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    border-radius: 2px;
    background: transparent;
button:active::after {
    background: rgba(0, 0, 0, 0.4);

It's worth creating the pseudo-element directly on the button and then altering its background on the :active state, rather than writing it all solely to the :active state so that the browser has less work to do on demand.

This technique can be used in conjunction with last week's trick by setting both ::before and ::after pseudo-elements and will, of course, work with :hover, :active or any other state.