Just recently I came across the greatest CSS trick I think I have ever seen. It’s called box-sizing: border-box. Basically, it modifies how CSS calculates the width of elements. Normally, elements have the property box-sizing: content-box. This means that the width of the element only applies to it’s content, and any pagging or border are added outside that width. This means that any time you add padding or border to an element, you have to recalculate your margins.
But then i came across border-box. This means width now includes padding AND border. So in other words the width you define the width of the element, no ifs ands or buts!
This single modification literally fixed 90% of my layout issues, you can read up on it at CSS-Tricks here. But it got me thinking, what other layout tricks are out there that I don’t know about?!? What tricks have you come across in your travels to achieve that oh so clean layout?
This gives actual centering, vertically AND horizontally. Of course, absolute positioning can be awful unless used carefully so it’s not a trick to be abused. Still, it always ends up as a mixin in my Sass files. Also useful to make your Codepen demos of small components look neat.
Of course, flex box exists, but this tends to be more browser compatible and you don’t need polyfills to use it for older browsers.
For me it must have been all the tricks with :before and :after, adding “content” properties to each. This gave me more flexibility in designing stuff where I would otherwise need to add more divs & spans.
You can use this to create very flexible lines of boxes - a kind of 1-dimensional grid. The following gives 3 unequal width boxes, each with centered text, all in a row taking up the full screen width. (This works in both Firefox and Safari.)
border:1px solid black;
float:left; /* if this is not there, boxes are on separate lines */
padding-top:20px; /* can be % */
<div style = "width:10%" class="pdg core" >left10</div>
<div style = "width:30%" class="pdg core" >middle30</div>
<div style = "width:60%" class="pdg core" >right60</div>
You can make any number of boxes. You can also make any box invisible, so it takes up the space but the result looks like completely arbitrary placing. To make the box invisible, do not include the border, and make the content a space - .