Thursday, September 17, 2015

Efficient CSS Using Child-Selectors

So, I'm working away on and I find myself forgetting this over and over. I figured it would be a good idea to write a blog post about it to remind me there's a better way. 

Here's a typical use of CSS to assign margin to some images: 

    .issuerpics { margin: 15px; }

<div style="text-align:center">
    <img src="=logobluecross.png" alt="Blue Cross" class="issuerpics" />
    <img src="=logoaetna.png" alt="Aetna" class="issuerpics" />
    <img src="=logocoventry.png" alt="Coventry One" class="issuerpics" />
    <img src="=logocigna.png" alt="Cigna" class="issuerpics" />
    <img src="~=logouhone.png" alt="United Health One" class="issuerpics" />

Note that each image has a CSS class assigned to it. It's a logical technique, but not the most elegant one. Below, the parent element (div) is assigned a class and then the CSS is written to style the child elements of that class. It's less code, more readable, and in general more elegant. 

    .issuerpics img { margin: 15px; }

<div class="issuerpics" style="text-align:center">
    <img src="=logobluecross.png" alt="Blue Cross" />
    <img src="=logoaetna.png" alt="Aetna" />
    <img src="=logocoventry.png" alt="Coventry One" />
    <img src="=logocigna.png" alt="Cigna" />
    <img src="=logouhone.png" alt="United Health One" />

In general, it's best to make the code as readable as possible. Less code is usually better as long as it doesn't sacrifice readability. This change accomplishes both. 

No comments:

Post a Comment