8 Clever Tricks with CSS Functions

    Anselm Urban
    Anselm Urban
    Share

    CSS is capable of much more than many web developers realise. The stylesheet language continues to get more and more powerful with every passing year, bringing functionality to the browser that otherwise would be fulfilled by JavaScript. In this article, we’ll take a look at eight clever tricks with CSS functions that do not require JavaScript at all.

    1. Pure CSS Tooltips

    A lot of websites still use JavaScript to create tooltips but it is actually much easier with CSS. The simplest solution is to provide the tooltip text in a data attribute in your HTML code, e.g. data-tooltip="…". With that in your markup, you can then place the following into your CSS to display the tooltip text inside the attr() function:

    .tooltip::after {
      content: attr(data-tooltip);
    }

    Quite self-explanatory, right? Of course, there is more code needed to actually style the tooltips but fear not, there is an awesome, pure CSS library for this exact purpose called Hint.css.

    2. (Ab)using Custom Data Attributes and the attr() Function

    We already used attr() for tooltips but there are some other use cases for it too. In combination with data attributes, you can build a thumbnail image with title and description using just one single line of HTML code:

    <a class="caption" href="#" data-title="Vulture" data-description="...">
      <img src="img.jpg" alt="Illustration"/>
    </a>

    Now you can use the attr() function to display the title and description:

    .caption::after {
      content: attr(data-title);
        ...
    }

    Here’s a working example of a thumbnail with animated captions that show on hover:

    See the Pen Thumbnail with Animated Captions by SitePoint (@SitePoint) on CodePen.

    Note: Generated content could be problematic in terms of accessibility. This article on accessibility support for CSS generated content is a useful read on that very topic.

    3. CSS Counters

    What you can do with CSS counters seems like magic. It is not the most well-known feature and most people probably would guess that it is not so well supported but actually, every browser supports CSS counters:

    See Can I Use css-counters? Data on support for the css-counters feature across the major browsers from caniuse.com.

    While you should not use CSS counters for ordered lists (<ol>), counters are great for things like pagination or displaying numbers underneath items in a gallery. You can also count the number of checked items which is quite impressing given how little code you need (and no JavaScript):

    See the Pen Selection CSS Counter by Will Boyd (@lonekorean) on CodePen.

    CSS counters are also great for dynamically changing numbers in a list of items which can be reordered by dragging and dropping:

    See the Pen CSS Counters drag-and-drop demonstration by SitePoint (@SitePoint) on CodePen.

    Just as with the last example, remember — generated content could be problematic in terms of accessibility.

    4. Frosted Glass with CSS Filters

    With iOS 7, Apple brought us the “frosted glass” effect — translucent, blurry elements that look like a frosted glass window. This effect is starting to appear in many of places, inspired by Apple’s implementation. Recreating this effect is a bit tricky — before there were CSS filters, you had to create the frosted glass effect with blurred images. Now that CSS filters are fully supported by almost all major browsers, it is much easier to recreate this effect.

    See Can I Use css-filters? Data on support for the css-filters feature across the major browsers from caniuse.com.

    In the future, we could create similar effects using backdrop filters and the filter() function which are both currently only supported by Safari.

    5. Using HTML Elements as Background Images

    Normally, you would specify a JPEG or PNG file as background image or maybe a gradient. But did you know that with the element() function, you can also use a <div> as a background image? Currently, the element() function is only supported by Firefox:

    See Can I Use css-element-function? Data on support for the css-element-function feature across the major browsers from caniuse.com.

    The possibilities are nearly endless, here is one example from MDN.

    6. Smarter Grids with calc()

    Fluid grids are a great thing but there are some serious problems. For instance, it is impossible to have a gutter on the top and bottom that is the same size as a gutter on the left and right. Also, the markup is really messed up, depending on which grid system you use. Even flexbox alone is not the ultimate solution but with the calc() function which can be used as a value in CSS, grids can become much better. In this tutorial here at SitePoint, George Martsoukos shows some practical examples, such as a gallery grid with perfect spacing. Using CSS preprocessors such as Sass, putting together a creative grid system can be incredibly simple and easy to maintain. With browser support also being nearly perfect, calc() is a handy feature you should definitely use.

    See Can I Use calc? Data on support for the calc feature across the major browsers from caniuse.com.

    7. Aligning position:fixed Elements with CSS calc()

    Another use case for the calc() function is aligning elements with a fixed position. For example, if you have a content wrapper with fluid spacing to the left and right, and you want to precisely align a fixed element inside of that wrapper — you’re going to have a hard time figuring out which value to choose for the “right” or “left” property. With calc(), you can combine relative and absolute values to perfectly align the element:

    .wrapper {
      max-width: 1060px;
      margin: 0 auto;
    }
    .floating-bubble {
      position: fixed;
      right: calc(50% - 530px); /* 50% - half your wrapper width */
    }

    Here’s an example:

    See the Pen Aligning “position: fixed” elements with CSS calc() by SitePoint (@SitePoint) on CodePen.

    8. Animations with cubic-bezier()

    To make the UI of a website or app more attractive, you can use animations but the standard easing options are pretty limited. For example, "linear" or "ease-in-out". Things like bouncy animations aren’t even possible with the standard options. With the cubic-bezier() function, you can animate elements exactly the way you want.

    There are two ways to use cubic-bezier() — understanding the mathematics behind it and building it yourself, or using a cubic-bezier generator.

    Honestly, I’d go with the latter.

    Conclusion

    A clever use of CSS functions not only solves known problems like establishing smarter grid systems but it also gives you more creative freedom. With browser support getting better and better, you should really take a critical look at your CSS and improve it with functions like calc().

    Frequently Asked Questions about CSS Functions

    What are the basic CSS functions I should know as a beginner?

    CSS functions are used to set the value of CSS properties. Some basic functions that every beginner should know include rgb(), rgba(), hsl(), hsla(), and calc(). The rgb() and rgba() functions are used to define colors, while hsl() and hsla() functions are used to define colors in terms of hue, saturation, and lightness. The calc() function allows you to perform calculations to determine CSS property values.

    How can I use the calc() function in CSS?

    The calc() function in CSS is used to perform calculations that can be used as property values. This function can use the “+” (addition), “-” (subtraction), “*” (multiplication), and “/” (division) mathematical operators. For example, you can use calc() to create a div that is always 50% of the viewport width minus 20 pixels like this: div { width: calc(50% – 20px); }.

    What is the difference between rgb() and rgba() functions in CSS?

    The main difference between rgb() and rgba() functions in CSS is that rgba() includes an alpha channel, which specifies the opacity of the color. The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque). For example, to set a semi-transparent red color, you can use: color: rgba(255, 0, 0, 0.5);.

    How can I use CSS functions to create gradients?

    CSS functions can be used to create gradients using the linear-gradient() and radial-gradient() functions. For example, to create a linear gradient that goes from red to blue, you can use: background: linear-gradient(red, blue);. Similarly, to create a radial gradient that goes from red at the center to blue at the edges, you can use: background: radial-gradient(red, blue);.

    Can I use CSS functions to transform elements?

    Yes, CSS functions can be used to transform elements. The transform property can be used with various functions like rotate(), scale(), skew(), and translate() to modify the appearance of an element. For example, to rotate an element 45 degrees, you can use: transform: rotate(45deg);.

    What is the purpose of the attr() function in CSS?

    The attr() function in CSS is used to return the value of an attribute of the selected elements. This can be useful for things like generating content. For example, you can use attr() to display the value of the “href” attribute of a link in a tooltip: a:after { content: attr(href); }.

    How can I use the var() function in CSS?

    The var() function in CSS is used to insert the value of a custom property (also known as a “CSS variable”). For example, you can define a custom property –main-color: blue; and then use it in your CSS like this: color: var(–main-color);.

    Can I use CSS functions to create animations?

    Yes, CSS functions can be used to create animations. The animation property in CSS is a shorthand property for eight different properties, including animation-name, animation-duration, animation-timing-function, etc. For example, to create a 2-second animation named “slidein”, you can use: animation: slidein 2s;.

    What is the purpose of the url() function in CSS?

    The url() function in CSS is used to include a file. The most common use of the url() function is to link to an external stylesheet or to include an image. For example, to set the background image of an element, you can use: background-image: url(‘image.jpg’);.

    Can I use CSS functions to create 3D transformations?

    Yes, CSS functions can be used to create 3D transformations. The transform property in CSS can be used with functions like rotateX(), rotateY(), rotateZ(), scale3d(), and translate3d() to create 3D transformations. For example, to rotate an element around the X-axis, you can use: transform: rotateX(45deg);.