Monthly Archives: September 2014


First-Child CSS Tip To Fix Margins

I have done many websites in the past and had to set specific attributes for multiple items that were really the same item but because of its positioning, I couldn’t use all the same values.  What do I mean with this?

Let’s say you have a column with 4 blocks in it.  We are gonna say it is the side bar and you have the following items in it:  Specials, Product of the Week, Upcoming Events and Sponsored Ads.  I am referencing a site I did for VIP Billiards.


Now in that side bar, you want spacing between each section.  So in this case, I used my <h3> tag to create the spacing and I set the value to 1.5em.  But when I do that, I feel like my spacing at the top of the column is too large.  How do we fix that in a quick manner without having to have a new class for the <h3> tag?


Simple, we add a “first-child” to the <h3> tag.  We re-adjust the {margin-top} to 1.0em; and then add the following code:

h3:first-child {

margin-top: .5em



By doing this, we give the first <h4> tag in that column only a .5em margin at the top and give the spacing for the rest a 1.0em margin.

Now we have nice spacing between the navigation bar and the column as well between each section.  And because we added a “first-child” for the <h3>, it works for any section that has an <h3> tag.


Using a first-child can fix other issues as well.  Maybe you want to set the spacing between a few images but you don’t want a margin to the left on the first image.  Use a first-child for your images.

Now if we can use a first-child, then that should mean we can use a “last-child” as well.  Test it out, let me know how it works for you.

Happy coding!!


PS:  10/25/2014 – Since writing this and making minor adjustments, I re-adjusted my <h3> by adding a padding-top: 6px; and a padding-bottom: 6px; and with the h3:first-child {padding-top:0px;}.  This helped with page layout a little better than how it is written above. CSS is so versatile that there are many ways to “skin a cat”.