5 CSS tips you didn't know you needed
Lynne Finnigan

Lynne Finnigan @lynnewritescode

About: Front-end engineer from Scotland, UK.

Location:
Scotland
Joined:
Apr 13, 2017

5 CSS tips you didn't know you needed

Publish Date: Nov 28 '18
1029 63

Having worked in web development agencies over the years, I've picked up some tips and tricks along the way. There are some things that I use day to day, that I barely even think about. Some of them are fairly standard, and others are a bit more unusual, but all of the snippets and examples below are things that I've used on client websites.

Transitions

By default on all of the websites I build, I always add a CSS transition on the links and buttons for their hover state. It just adds a nice effect on hover, and takes away from that harsh/abrupt change when you interact with a button or link.

// Background colour transition
transition: background 0.2s ease-in-out;
Enter fullscreen mode Exit fullscreen mode

For a button I'd most likely add the transition for the background colour as shown above, for a link I'd set the transition property to all (transition: all 0.2s ease-in-out) which could allow me to transition the hover colour and border for example.

I also never use text-decoration: underline. You don't have much control using that, whereas you can use a bottom border to get a much nicer effect. Padding allows for better spacing, and you can even transition or animate the border if you'd like.

.link {
    transition: border 0.2s ease-in-out;
    border-bottom: 1px solid transparent;
}

.link:hover {
    border-color: blue;
}
Enter fullscreen mode Exit fullscreen mode

Background overlay

Say you have some text, positioned absolutely on top of an image. But the background image is too bright, making the text unreadable. You could add another div in there somewhere to create a dark overlay behind the text, however this is not great and adds an extra empty div that is not really necessary.

Pseudo-elements to the rescue!

Using the :before element means we can also apply it if a certain class is added to the div for instance. Below is an example of how I would achieve this overlay background:

The key part in the above code is setting your overlay colour, and opacity level. This can be any colour, I've just used black and white as an example:

//Black overlay - 0.5 opacity
background: rgba(0,0,0,0.5);

//White overlay - 0.2 opacity
background: rgba(255,255,255,0.2);
Enter fullscreen mode Exit fullscreen mode

Multi-line underline effect

The pen below is something that may or may not be useful to people, but it is something I was asked to do on a client website. It allows the ability to have a bold underline effect which will span across a sentence to the length of that sentence, even if it's wrapped over multiple lines.

Even if this doesn't apply to your design, or requirements. It can also be used for things such as a link hover effect like the one shown below:

Sticky elements

Need an element to stick on scroll, but don't want to use JavaScript, or a plugin, or the height of your content is dynamic and likely to change? position: sticky is your friend.

position: -webkit-sticky;
position: sticky;
top: 0px;
Enter fullscreen mode Exit fullscreen mode

This was incredibly handy for me when I had to have a sidebar stick next to an accordion element. Because of the accordion opening and closing, I would have had to calculate the height or use some other complicated method, when position: sticky just worked straight away. The only thing I've found to look out for is that it doesn't work when the body element is set to overflow: hidden, and is not supported in IE11 (it just doesn't stick, and Edge is fine).

Prevent highlighting

Being able to select text on a website is fairly standard and expected, however I've found occasionally that the user can click multiple times on an element (for example a carousel arrow) and it selects/highlights the element.

To prevent this, you can use the following snippet:

.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
       -moz-user-select: none; /* Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
}
Enter fullscreen mode Exit fullscreen mode

If you got this far, thanks for reading! I hope this comes in handy for some people and I hope to do some further posts with some more day to day snippets if that is of interest to anyone.

Follow me on twitter and instagram for more dev related stuff!

Comments 63 total

  • Emran
    EmranNov 29, 2018

    Thanks. for share your experience.

  • Jeremy
    JeremyNov 29, 2018

    Have been using CSS for a long time now and I had never come across sticky or user select none before!

    Thanks for that ☺

    • Lynne Finnigan
      Lynne FinniganNov 29, 2018

      You're welcome :)

      I think for a while position sticky didn't have much browser support, but now it does other than IE11. At least because it's css, it doesn't break anything in IE11, it simply just doesn't stick!

  • Shahidul Islam Majumder
    Shahidul Islam MajumderNov 29, 2018

    Multi line hover effect is really cool. Thanks for sharing the tricks.

    • Lynne Finnigan
      Lynne FinniganNov 29, 2018

      No problem, I really like the effect too! Hopefully some of them come in handy :)

  • Robin Kretzschmar
    Robin KretzschmarNov 29, 2018

    user-select was new to me, thanks for sharing this! :)

    • Lynne Finnigan
      Lynne FinniganNov 29, 2018

      No problem, it was a strange one at the time, took a while to find a solution!

  • Thoby V ijishakin
    Thoby V ijishakinNov 29, 2018

    Wow awesome tips. Thanks for sharing.

  • Nathanael Demacon
    Nathanael DemaconNov 29, 2018

    The most useful trick I use in every project is:

    * {
      box-sizing: border-box;
    }
    
    Enter fullscreen mode Exit fullscreen mode

    Which prevent breaking box dimensions with margin, padding or borders.

    • Sdu
      SduNov 29, 2018

      This should be default

    • JavaMajk
      JavaMajkNov 30, 2018

      Yup, ..to be extra safe :D

      
        html {
          box-sizing: border-box;
        }
        *, *:before, *:after {
          box-sizing: inherit;
        }
      
      Enter fullscreen mode Exit fullscreen mode
      • Nathanael Demacon
        Nathanael DemaconNov 30, 2018

        It seems like the same thing? :(

      • Jonny Goodwin 🚀
        Jonny Goodwin 🚀Dec 4, 2018

        I think that using box-sizing: inherit;’ can be bad. If you do this, and decide to change box-sizing on an element, all of that elements children will also have their box-sizing changed.

        Unless you are sure you want that to happen, it’s probably best just to use ‘box-sizing: border-box;’ to ensure that all elements use ‘border-box’. If any elements need a different box-sizing, you would override it with more specificity.

        • JavaMajk
          JavaMajkDec 6, 2018

          Yeah indeed, things can get messy in this case.

          • Daniel Tonon
            Daniel TononDec 27, 2018

            I was a box-sizing: inherit; person, then I realised this is super useful:

            .page-restrictor {
              max-width: 1200px;
              margin: 0 auto;
              padding: 0 20px;
              box-sizing: content-box;
            }
            

            It means that when the screen is less than 1240px wide, it will have a 20px gap down either side of the screen with no need for media queries.

            This technique doesn't work with box-sizing: inherit; though.

      • Giacomo Sorbi
        Giacomo SorbiDec 4, 2018

        Mh, the * selector is relatively very expensive: I would use it rather sparingly.

  • Jan-Philipp
    Jan-PhilippNov 29, 2018

    Thanks for the tipps!

    Just starting out on Web Dev. I will copy your blending for the links this evening on my project :)

  • Alex Lohr
    Alex LohrNov 29, 2018

    A CSS trick with an effect on JS: pointer-events: none will remove an element from the DOM event tree even if it is in the foreground, which means that if you capture click events, you'll receive the parent. If you are using event.target, you'll save yourself some steps of filtering.

    Interesting fact I found out: if you add text nodes via appendChild, some browsers will handle them as own elements inside the DOM event tree.

    • Mattia Astorino
      Mattia AstorinoDec 1, 2018

      you need always to double check with js because removing pointer-events: none the element will be targettable even if it is eg. disabled.

  • Mathiu
    MathiuNov 29, 2018

    This is awesome, I actually never saw proper text underline with hover, it works even when you change line-height and have more than 2 lines of text.

    Thanks for sharing!

  • Jake Wesorick
    Jake WesorickNov 29, 2018

    Pretty sure you're not supposed to prevent highlighting as thats there for people with disabilities.

    • Lynne Finnigan
      Lynne FinniganNov 29, 2018

      When I had to use this it was to prevent the highlighting when you clicked multiple times on a carousel arrow really fast. I wouldn’t apply it to text or anything like that - I would have no reason to.

      I can’t find much info on this specific property and accessibility issues, where did you find that information?

      • Jake Wesorick
        Jake WesorickNov 30, 2018

        I am wrong. I was thinking of this: a11yproject.com/posts/never-remove.... As long as it still has an outline when it's focused you're safe.

        • Lynne Finnigan
          Lynne FinniganNov 30, 2018

          It was worth checking again, considering how screenreaders work! Thanks for sharing the issue with removing the outline on focus 🙂

    • APixel Visuals
      APixel VisualsDec 4, 2018

      Can also be used to prevent selection of images by accident.

  • astodev
    astodevNov 29, 2018

    Here is a nice CSS tip (or CSS idea) for mobile design that a co-worker showed me today:

    On mobile make your buttons wide so they're easy to click.

  • Precious adeyinka
    Precious adeyinkaNov 29, 2018

    wow, thank you so much for this article it came in handy, I learnt newer features of css.

  • Mr Daily
    Mr DailyNov 29, 2018

    Cool

  • Akshay Kadam (A2K)
    Akshay Kadam (A2K)Dec 1, 2018

    Thank you, Lynne, for that wonderful multi-line effect.

    I saw it somewhere but forgot about it. Soon I'll use it on my next project.

    I've made some Pens for practicing these & to simply copy-paste next time I use it. Of course, I've given credits to you on top of each CSS file. Here are the links -

    1) Transitions - Button & Link

    2) Background Overlay

    3) Multi Line Underline Effect

    4) Sticky Elements

    5) Prevent Highlighting

  • Flare
    FlareDec 1, 2018

    a big thank you for the writer, i learned new things from this article.

  • Shubham Battoo
    Shubham BattooDec 1, 2018

    Really cool tricks.

  • Allan N Jeremy
    Allan N JeremyDec 2, 2018

    The pseudo-selector background overlay is neat! Knew about pseudo-elements but never occurred to me to use them for the background overlay. Always added that extra inner div. Time to refactor!

    The underline one was pretty cool too. Heck, they were all interesting in their own way.

    Thanks for sharing Lynne

    • Lynne Finnigan
      Lynne FinniganDec 2, 2018

      I'm glad it helped! These are things I've discovered along the way, thought it would be good to share :)

  • Osama Adil
    Osama AdilDec 3, 2018

    Beautiful! I was looking for these tips for a while now. Thanks!

  • leob
    leobDec 4, 2018

    Never ceases to amaze me how much "stuff" there is in CSS, it's endless. Implementing a CSS processing/browser rendering engine must be one of the most dauntingly complex pieces of engineering you can imagine.

    • Lynne Finnigan
      Lynne FinniganDec 4, 2018

      I know, right?!

      • leob
        leobDec 4, 2018

        I saw a statement recently that "CSS is the most complex programming language that exists" ... I don't know if it can really be considered a programming language (in the Turing sense), but it is really insanely complex, especially because of its long history and never ending evolution, which means that there are always at least half a dozen different ways to do something.

        Anyway, some really great tips and techniques here, thanks for the article! "sticky" is especially a cool one, and the transition tip is simple but very useful.

  • Anurella
    AnurellaDec 4, 2018

    thank you

  • Maxime Simoncelli
    Maxime SimoncelliDec 20, 2018

    Really love that multiline effect, thanks for sharing !

  • Daniel Tonon
    Daniel TononDec 27, 2018

    Hot tip:

    transition: 0.2s;

    =

    transition: all 0.2s ease;

    😁

  • Max Jann
    Max JannJan 3, 2019

    hey thanks i like the time delayed underline on hover

  • mlevesquedion
    mlevesquedionJan 28, 2019

    For that last one (prevent highlighting), if you're using bulma you can use the "is-unselectable" class.

  • Gulshan
    GulshanMay 3, 2019

    that's some really cool trickrey 😃 well, for background overlay example, I use blend-mode which is really easy. And for the text underline I've been using box-shadow but that hover effect is really cool! I'll try that one.

  • Azkar Moulana
    Azkar MoulanaJun 3, 2019

    position: sticky is your friend.

    Not supported by all the legacy browsers. Even chrome gives the partial support. But a very handy style rule, browser supports will be granted in near future.

  • Peter David Carter
    Peter David CarterSep 21, 2019

    I learned so much! 🙃

Add comment