Friday, January 24, 2014

Prevent common problems when writing CSS from scratch

Many times when I started writing the classes of a brand new site, I had two problems that bothered me very much: keeping the footer always at the bottom of the page - even if the page has few content - and using padding values in divs without influencing the overall width of the div.

Then I decided to always put the same basic classes on the css file, no matter what the layout would look like:

Solving the footer position issue

Prevent common problems when writing CSS from scratch

First of all, your HAML structure should be like this:

wrapper
   %header
     // content of the header
   #main-content
      // content of the body
   %footer
      // content of the footer

Then, the following classes should do the job:

html, body {
    margin: 0; padding: 0;
    height:100%;
}

#wrapper {
    min-height: 100%;
    position: relative;
}

#main-content{
    padding: 10px;
    padding-bottom: 60px;    /* Height of the footer */
}

footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 60px;    /* Height of the footer */
}

This should keep the footer at the bottom as you add more content to the page or if don't have enough content to force the footer down.

Avoiding problems width paddings and widths

Imagine that you created a layout that has 3 boxes of the same width aligned besides each other. All of these boxes are divs with 100px of width inside a div of 360px of width. The HAML structure would be like this:

.boxes-container
   .box xxx
   .box xxx
   .box xxx

and this would be the CSS:

.boxes-container{
    float: left;
     width: 360px;
    background: #000;
}

.box {
    background: none repeat scroll 0 0 #FFFFFF;
    float: left;
    margin: 10px; padding: 10px;
    width: 100px;
}

Regularly, CSS would add the padding value to the with of the box div, causing the last one to fall down, because the sum of the elements width would be 420px that is larger than the 360px of the box-container. ( Each div would add 100px of width with 10px of margin-left and 10px of margin-right width 10px width 10px of padding-left and 10px of padding-right. 140px of overall width x 3 divs)

Prevent common problems when writing CSS from scratch

If we use the CSS box-sizing property, though, we can fix this problem by keeping the padding value inside the div and mantaining the correct width. I usually apply the universal selector to all elements and pseudo-elements on the site:

*, *:before, *:after {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

This is the result of using the box-sizing property:

Prevent common problems when writing CSS from scratch

So remember: Using box-sizing to all elements on the CSS and position absolute to the footer can save you from a lot of headache. :)