Thursday, September 17, 2015

Efficient CSS Using Child-Selectors

So, I'm working away on acaexpress.com 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: 

<style>
    .issuerpics { margin: 15px; }
</style>

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

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. 

<style>
    .issuerpics img { margin: 15px; }
</style>

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

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.