Hacker News new | past | comments | ask | show | jobs | submit login
A Collection of CSS Tips (github.com)
112 points by AllThingsSmitty on Dec 14, 2015 | hide | past | web | favorite | 48 comments

Pro CSS tip #1 (emphasis on the 'Pro' more than the 'CSS'): If you want to be a professional and work as part of a team, get better at documenting your code. Write code that other people can maintain when you're not available. Comment your code. Write actual docs. Write tests.

Pro Tip 1.1 -> Do not comment what your code is doing (code should be self-explanatory). Comment why something is done this or that way.

I disagree. I comment what my code is doing all the time, because those comments serve as 'headers' for the various tasks being performed. It's called "chunking" and it is a very powerful pattern for making things easier to understand.

Secondly: your code isn't self-explanatory, no matter how much you wish it were.

$yourFavoriteLanguage already has a mechanism for chunking. They're called functions.

(Okay, so if $yourFavoriteLanguage is CSS, maybe not.)

My only thing is that there are times where relatively unknown structures (to the team anyway) can be used to achieve a task. Inline comments can alleviated some time wasted doing external lookup when trying to debug something in the function:

    ExecutorService exec = Executors.newSingleThreadExecutor(); //instantiate thread manager
    Future<?> future = exec.submit(serviceTimer); //queue thread for async execution
    exec.shutdown(); //execute queued thread and deny additional requests for execution
All of these inliners are explained in the docs, but sometimes it gives a warm and fuzzy when the author explicitly states what is happening with a comment.

All three of those are just bad function names, though.

would all be a far better solution than putting an inline comment on everything.

No, the original function names are better than your replacements, because they accurately describe what the functions will actually do instead of assuming they know what the user wants. Your names imply non-trivial differences in the way the functions work. These are library functions, so their names must be carefully chosen to imply only what the contract of the actual method supports. In particular:

You lose information about the thread count (single thread). Also, a nitpick I know, but in Java new means instantiate, so just say new and save typing. Also, an executor is not guaranteed to be a thread manager in any meaningful sense. It is only guaranteed to be an Executor.

This may not actually be async. 9/10 it is, but the interface does not guarantee async, just a de-coupling from queuing and execution.

This misses the fact that calling shutdown will deny future tasks from being queued after it is called.

This is actually a great example of why function names are not a sufficient replacement for appropriate comments.

While I agree, those are all built-in functions. I suppose that's why there's the doc-on-highlight feature. I'd need to wrap them if I wanted just to rename them.

Those functions don't always align with the problem model, and they often have a cost associated with their use.

You should take the advice to mean "Don't comment on how your code is doing what it's doing, comment on why it's doing that." An English transliteration of a source code statement usually isn't very helpful.

In general I agree with you, but specifically when using comments as headers, I think it's fine to describe briefly what it's doing (and how), in the same way that a header in a book often describes what the chapter is about.

Sure, but a header in a book should just repeat the contents of the chapter but worded differently. In the same way, comments should not just reiterate the code.

In the header case, the comment is a summary of what the code is doing, which I think is fine if it allows you to understand the code block quickly without reading it in detail. That's different from a comment like "Add one to index" followed by "index = index+1", which is the canonical/trivial example of what the advice is intended to recommend against.

Comments like "add one to index" are a symptom of laziness, not of commenting about the wrong thing. As an example, here is some of my actual code:

    /* Prompt for scheduler. */
    if (!flag_scheduler_selected && !flag_no_prompts) {
        option_scheduler = prompt_scheduler();
The purpose of the comment is not to tell you what it is doing or why I'm doing it. The comment is there to tell you that what I am doing now has nothing to do with what came before. It signals a mental context switch. Without the comment, you wouldn't be able to easily scan the code and see where different things are happening.

Especially when the code is changed and the comment is now incorrect...

The problem isn't the now incorrect comment, it is the person that didn't update the related comment.

A wiki page/word doc is even easier to forget to update than in-line comments.

That is a "useful" code smell: if the code and the comments disagree, assume both are potentially wrong, handle with extreme care, and fix ASAP where possible.

How do you see that working for CSS?

Is this:

    /* This should have round corners */
    .this {
any better than this?

    /* Make this have round corners */
    .this {
Really, I look at the boilerplate how-to-comment discussion thread here, and it seems utterly irrelevant to CSS.

I think this applies more in terms of 'this fixes a bug in X browser where Y happens'.

That's a good answer.

Pretty good suggestions. Here are some thoughts that I had reading the article;

* Suggestions are newly browser supported CSS properties in lieu of the earlier ones. It is always easier to use new and improved ones than making it work on olden browsers.

* Most of them are also of how you should scaffold your styles and not necessarily the nitty-gritty of writing better CSS.

For instance, vertically centering a block element inside another block element can be done in various ways

* display:table, display:table-cell with a vertical-align: middle method for olden browsers is indeed of of those sure-shot method that works across a plethora of browsers.

* The translate method for newer browsers including IE10+ with some quirks.

* And of course, the Flexbox method, which is the current talk of the CSS town.

Well, centering in CSS has even spawn a whole industry - http://howtocenterincss.com/.

Liked the idea of ":not()". This is something most developers overlooked.

The blanked statement and advice to 'use of SVG for icons' is something I can debate. This is not a binary statement/switch that you can make decision on. I'd rather decide on the method based on the requirement at hand and how it is being delivered. Even in dev-time, I do setup such that the team have to just drop in SVGs but eventually, a task runner takes care of the final icon set - be it as a @font-face - either served separately or BASE64 encoded with the styles (for something within a size budget that we set for the font-family).

I'd be pointing anyone wishing to improve holistically from a n00b to a better player would be to look at the likes of http://codeguide.co/, http://sass-guidelin.es/ et al. And get http://caniuse.com/ hooked up in some way, either via your IDE or leave it open in a browser tab.

Edits: I thought Hackernews supported Markdown!

One thing to watch for when using :not() is that it has high specificity.

Yup. More precise, it has the same specificity as the selector it is negating in its "parameter" (which must be a "simple" one, not compound). My favourite CSS bruteforce hack [1] for boosting specificity exploits this:

    *:not(#\0):not(#\0):not(#\0) {} /* three ID strong anything */
[1] Never used it in meaningful context, actually.

Don't think the `:not` tip is good. You're adding 1 more level specificity to all of nav items except the last one as opposed to that 1 level to just the last one. Makes it a bit more annoying to overwrite when it comes to it.

The "Use Attribute Selectors with Empty Links" tip[0] seems pretty pointless:

  a[href^="http"]:empty::before {
    content: attr(href);
So if there's no link content, insert the URL as the content. That seems like a content issue and not a styling/CSS issue, and would break with any links where the "content" is a background image.

[0] https://github.com/AllThingsSmitty/css-protips#use-attribute...

An empty <a> link will also likely fail accessibility tests and while the presentation is works for visual keyboard-only users, screen reader users will probably have problems.

I'm curious if this helps screen readers.

    .no-svg .icon-only:after {
      content: attr(aria-label);
I would think the `:after` would make the aria attribute apply to a new pseudo element, which may or may not do much good.

That's a good point. I'll need to dig into it a bit more.

Firstly, thank you to the writer, this was a nice short read.

However, It's funny, there are so many of these collections of CSS Pro Tips, though as someone who writes CSS, I feel the complexity is not in these general rules, but lies more in how CSS is organized for readability, how to write _composable_ and _reusable_ CSS components, and the like.

I'd love to see more articles on how people organize their CSS (either with BEM, SMACSS, or other creative frameworks), or how they create reusable CSS components to effectively add to an overall styleguide, rather than one-off tricks. Or how to reduce unused CSS clutter, or make _huge_ performance gains by doing certain things.

A few weeks ago, I came across this great article by @fat [1] and I think this is infinitely more helpful for the common beginner than a few tips. Using :not in CSS, vertically-aligning items, or making comma-separated lists using pseudo-elements may be helpful, but those can be easily Googled.

[1] https://medium.com/@fat/mediums-css-is-actually-pretty-fucki...

This was a good read. Reminded me of reading the trello css style guide https://gist.github.com/bobbygrace/9e961e8982f42eb91b80

I'm bad a css. It takes me hours to clobber together a bootstrap page. Can a real pro tell me if these tips are good?

The use cases are mostly really specific. Rather than focus on "tips" like this, I think "best practice" guides are much more helpful. Actually thinking through questions like how much should I link my DOM to my CSS (e.g., #container > p vs p.class_name) is generally more helpful imo than specific tasks that you can google.

These tips are neat but are not going to make you a pro. What will make you a pro is understanding the box model, colors / gradients, and selector preference/scope.

Any suggestions for good places to read up on these? I am a 90% back end dev that needs to delve into front end from time to time. I never feel like I understand CSS.

Maybe it will be too easy for you, but have you checked the html/css course on codeacademy.com ?

Some good, some questionable.

Being pro in css however lies within writing readable, maintainable, well documented css and these tips focus on none of that and will not make you any more or less pro than you were before reading them :)

Same here, I've mainly learned from just guess and check. Any tutorials I've tried (admittedly not many) are too basic and haven't given me a good mental model of how to approach a problem with CSS.

A lot of these are actually bad practice, or things you should already know. Before you use any of them, you should research each of the rules separately to see how they work.

Code maintainability is #1 in css, and is the hardest thing to do. The main focus should be on that, and not trying to be clever or tricky.

I think more needs to be made of this statement:

Watch for some buggy behavior with flexbox in IE11.

"Some buggy behavior" may more or less mean "it completely doesn't work in IE11" (which still has very significant market share) unless you start researching how to write cross-browser flexbox (at which point, welcome to trawling StackOverflow and feeling like you're almost back in the old days of crazy CSS browser hacks).

There will always be crazy CSS browser hacks as long as browsers seem incapable of having CSS implemented correctly.

eh vertical align with flex is very wonky. better use the position relative + transform -50% trick


alas, css-tricks has it all already

My tip is to avoid the use of tag names to style your page. Use classes instead.

Go further and investigate BEM naming conventions or better. Start creating components ( React, Web components, etc. ) that have encapsulated CSS.

Are you saying use <div class="heading"> vs <h1> or even <span class="bold"> instead of <b> or <strong>? because if so I disagree. Just on accessibility grounds this is a terrible idea.

I also disagree strongly with using encapsulated CSS everywhere except for individual widgets (and even then, where possible widgets should inherit styling in a sensible way -- otherwise a list row that goes in a main window table needs to be implemented separately from a list that goes in a sidebar, etc.

What I think is bad is having a convoluted CSS hierarchy. Having one or at most a few big standardized containers (e.g. document, tool-palette, browser) which receive reused styles and inline or very local css for specific cases allows you to implement preference settings, high contrast modes, etc. This is how actual desktop applications tend to work and they're a heck of a lot more complex than most websites.

I'm actually saying giving a class name to all elements that you use inside the body tag.

Really good reference is the new Calypso [1] Repository which has some really nice examples [2].

To answer specifically to your example. I usually write something like this :

    <h1 class="heading">Use <strong class="heading-keyword">classes</strong> instead of tag names</h1>
Semantically the css looks much better

    .heading { ... }
    .heading-keyword { ... }
Also keep in mind that CSS has built-in specificy, which is a game-changer and can turn your code into a nightmare. For your example I would never write ( using the same markup ) :

    h1 strong { color: blue; }
    strong { color: red; /* won't work */ }
because to override it i would need to include the hierarchy all the time.

1: https://github.com/Automattic/wp-calypso/ 2: https://github.com/Automattic/wp-calypso/blob/a7478174b04417...

> Are you saying use <div class="heading"> vs <h1> or even <span class="bold"> instead of <b> or <strong>? because if so I disagree. Just on accessibility grounds this is a terrible idea.

Nothing stops you from styling classes in your CSS while still using meaningful tags in your HTML :)

Exactly, so you can express intent with the tag ("this is a major heading") and presentation with CSS ("and it's in Times Bold 24px").

I appreciate the feedback everyone. Thanks for taking a moment to comment.

Applications are open for YC Summer 2019

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact