10 CSS Pro Tips

GitHub Octocat Ninja

There are lots of resources for cool CSS implementations, like animating elements and applying complex effects, but often it’s the little things that are the most useful. Those aren’t flashy enough to get mentioned in books and articles. They are the finesse techniques that experienced developers use to make their work more elegant and their workdays shorter. Here are my ten favorites:

1. Smart text case

Coding for maximum control of casing is particularly useful on buttons. In my experience the Business is always changing their minds on button casing and using the most adaptable capitalization when coding will make it simple to change all the cases sitewide with a single line of CSS. My tip is to use title case. That is hand tuning to a mix of upper and lower case, where insignificant words like “to” and “and” are not capitalized, but everything else is. It’s the only type of casing CSS can’t achieve. In the example below I have five identical buttons with the words “Add to Cart” on them. I’ve used only CSS to change the capitalization.

See the Pen Casing by Connie Finkelman (@pixelslave) on CodePen.21122

2. Smart line breaks

Line breaks are the result of text automatically wrapping in its container or the application of the HTML tag “<br />”. We all know that using break tags to introduce vertical space into a layout is the mark of an amateur coder, but now that we are using responsive layouts and building code for use on devices of greatly varying widths, we begin to see more subtle gotchas. For example in the menu snippet below, breaks have been used to balance the wrap and control where the ampersand is placed.

That’s fine until you need to transform this menu for a tablet or a phone and you want the menu text all on one line. You can use CSS to set the break tags to “display: none”, but there are more elegant ways to provide for customizing line breaks. The first is with CSS white-space formatting.

See the Pen Line breaks by Connie Finkelman (@pixelslave) on CodePen.21122

The second way to accomplish this is with spans or other inline HTML elements. (By “inline” I mean the opposite of “block”. See this explanation is you are unclear about the difference.) Using these wrappers is a semantic approach that is well suited to content that needs separation due to its meaning and context. For example, if you have a price label and a dollar amount and you want the ability to stack them.

Our Price: $19.99

To accomplish this you simply wrap each part in a label, span, strong, or em element and either float and clear, use flex, or give each a 100% width and center text align. The added advantage here is that you now have hooks for additional styling.

See the Pen Wrapping with flex by Connie Finkelman (@pixelslave) on CodePen.21122

3. Definition lists

In my experience, the definition list is one of the least used HTML structures but it is one of my favorites. I love it because it is semantic and establishes a relationship between two pieces of related content. That is a scenario we see often on transactional sites, for example, in a cart totals and account information. It can give you an effect similar to the tab spacing you get in word processing without locking you into a horizontal layout.

See the Pen Definition lists by Connie Finkelman (@pixelslave) on CodePen.21122

4. Namespacing

There are lots of great resources for naming and applying CSS classes, one of the best being Jonathan Snook’s SMACSS. But to me, one of the most important practices is separating styling classes from programming hooks. Enterprise code often has many developers modifying it on a continuous basis and it is refactored often for styling changes. If you use a generic styling class such as “full-width” as a hook for JavaScript your code will get broken when someone removes or changes that class and it will be your fault for not communicating the role of that element. Since HTML elements can have many classes, I always create a namespaced class for JavaScript hooks that will signal to any developer who comes after me the significance of that element. For example, I might create a class called “js-tooltip-trigger”. That makes it clear what’s going on with that element and protects the functionality.

4. Doubling weight

To me, the most important aspect of CSS authoring is controlling the specificity or weight of CSS rules. We want to keep rules as weak as possible so they can easily be extended for more specific cases later in the style sheet. Sometimes we have a generic class that needs to be given a little more strength. (This happens when you apply multiple generic classes that may have duplicate rules that contradict each other. Which ever one comes last in the style sheet wins. You may want to allow the earlier rule to always win.) We don’t want to make a rule too strong, so adding “!important” to it is out of the question. We can’t add an HTML element to it because we want it to be universal.

The best option is to add an additional class to it. We could pick a class we expect it to have as an ancestor, but that’s not guaranteed. The answer? Double it! by chaining a class to itself (“.stong.strong”) we double its weight without creating a dependency. Is it a hack? Maybe. But it’s valid CSS and incredibly useful, so that’s good enough for me.

5. The magic number

1.2em seems to be sort of a magic number in CSS. It is the normal line height and it is also the amount of left-side space a list needs if it has bullets on it. Resets sometimes strip off all the margin and padding from elements. This makes sense because they are used for structural elements such as navigational hierarchies more often than they are used as simple text lists. This leads to a situation where the bullets fail to show up on a list or the bullets are too far to the left, appearing outdented in relation to the surrounding paragraphs. Applying 1.2 ems of margin to your list cures this.

See the Pen 1.2em by Connie Finkelman (@pixelslave) on CodePen.21122

6. //#end

When you’re writing SCSS (SASS or LESS) you often have extensive nesting. Even if you don’t nest deeply you may have many siblings under a parent class or ID. No matter how much of a CSS ninja you are you will eventually hang a closing tag. I spent countless hours trying to debug huge blocks of SCSS looking for a missing or duplicated closing bracket until I started putting comments after the main closing tags in a block. I do this as soon as I open the class or ID declaration, rather than waiting until it fills up. There’s no downside to overdoing it, since comments are stripped out in compile for production-bound code. Both CSS and JS style comments work in SCSS. For example:

/*.article */

I also hand-code HTML, and I’ve also wasted many hours of time trying to troubleshoot broken CSS only to find that the real problem was a broken DOM. It’s a good idea to mark these as well, for example:

</div><!--/.article -->
</div><!--/#mainContent -->

7. Line flag classes

This one may be a bit controversial, but I find it to be a huge timesaver. I currently work in .Net with a very large codebase. I often find it difficult to figure out where dynamic content is coming from. For example it may be the result of a multipart conditional that has half-a-dozen possible outputs that have different values but identical markup and CSS classes, or it may have a pattern of markup, ids and classes that is not unique in the project and could have originated in one of several .asp files. When I’m trying to narrow down the source of this output I do a “find” to get a list of all of the possible sources, then I add a class that references the line number of each, e.g. “l4573”. That tells me conclusively which instance I’m working with.

I did this once for a table that had separators I was trying to eliminate. Flagging the line numbers showed me that these separators were coming from 6 different code blocks and it made the job so much less frustrating to know which one I was working with in each case.

When you’re done with the current task you can take these markers out or leave them in. Leaving them in makes it simple to locate the code later, as this class will be unique. (The chances of multiple elements falling on the same line number in a single document is nil and the possibility of this happening across several documents is also nil unless the documents are identical.) The downside is that you’re adding additional markup in the form of a CSS class that has no CSS functionality. That may bother CSS purists. The upside is that you’ll be able to take a longer lunch hour. For me it’s a no-brainer.

8. CSS Wayfinders

There is no “==” in CSS syntax. That makes this an extremely useful identifier in CSS blocks. If you comment each CSS section or SCSS include with this character pattern you can easily find your way in large CSS documents by simply searching for it. It looks like this:

/* ==Navigation */

You can take it a step further by coming up with your own scheme, such as using the word “page” + the id of a page’s body to introduce a block specific to a certain page:

/* ==page #checkoutPage */

9.Codepen autoprefixing

It’s easy to see from these blog posts that I love Codepen. I work in big enterprise projects with compiled code (including CSS and JavaScript that has to be built on each change). Being able to extract just the piece I’m working on and have it all in one place with instant updates saves me hours. Among the many great features of Codepen is the ability to automatically generate autoprefixing for CSS properties like “flex” that aren’t fully supported in all browsers. This is under “Settings” –> “Vendor Prefixing”. To use it, click the “View Compiled” button that will appear on your CSS panel when prefixing has been enabled. You can easily copy this to your project’s CSS file. I routinely paste my CSS into Codepen just for this function.

10. Codepen CSS validation

If you need to validate your CSS, LESS, SASS or SCSS the quickest and most reliable way I’ve found to do this is to paste it into Codepen’s CSS panel. It not only  flags errors it also tells you how to fix them. I do this on at least a weekly basis because if you’re hand-coding CSS you will make a typo sooner or later.

Leave a Reply