search
HomeWeb Front-endCSS Tutorial8 Clever Tricks with CSS Functions

8 Clever Tricks with CSS Functions

The power of CSS is far beyond many web developers' imagination. Over time, the stylesheet language has become more and more powerful, bringing functions to the browser that originally required JavaScript to achieve. This article will introduce eight clever CSS function tips that require no JavaScript at all.

Key points

  • CSS functions can be used to create various effects and functions such as tooltips, thumbnail titles, counters, and frosted glass effects without JavaScript.
  • calc() Functions can be used to create smarter grid systems and alignment of fixed position elements, providing greater flexibility and precision in design.
  • The
  • CSS function also allows creative animations using the cubic-bezier() function, as well as the potential to use HTML elements as background images using the element() function, although the latter is currently only supported by Firefox.
  1. Pure CSS Tooltips

    Many websites still use JavaScript to create tooltips, but in fact it is easier to use CSS. The easiest solution is to use data properties in HTML code to provide tooltip text, such as data-tooltip="…". With this tag, you can put the following into CSS to display tooltip text within the attr() function:

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

    It's very simple and clear, right? Of course, more code is needed to actually style the tooltips, but don't worry, there is a great pure CSS library specifically for this purpose called Hint.css.

  2. (abuse) custom data attributes and attr() function

    We have used attr() for tooltips, but it has some other use cases. Combining data properties, you can build thumbnail images with titles and descriptions using just one line of HTML code:

    <a class="caption" href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b" data-title="秃鹫" data-description="...">
      <img src="/static/imghwm/default1.png"  data-src="https://img.php.cn/upload/article/000/000/000/174011191897662.jpg?x-oss-process=image/resize,p_40"  class="lazy" alt="8 Clever Tricks with CSS Functions " />
    </a>

    You can now use the attr() function to display the title and description:

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

    This is a working example of a thumbnail with hover display animation title: [CodePen example link] (assuming that CodePen link should be inserted here)

    Note: The generated content may have problems with accessibility. This article on accessibility support for CSS generated content provides a useful interpretation of this topic.

  3. CSS Counter
  4. You can use CSS counters, which seems like magic. It's not the most well-known feature, and most people may think it doesn't support it very well, but in fact, every browser supports CSS counters: [Can I Use css-counters?] (assuming Can I Use should be inserted here Link)

    While you should not use CSS counters for ordered lists (<ol></ol>), counters are great for pagination or displaying numbers under items in gallery. You can also count the number of selected items, which is very impressive considering that you need very little code (and no JavaScript): [CodePen sample link] (assuming that CodePen link should be inserted here).

    CSS counters are also great for dynamically changing numbers in the project list, which can be reordered by drag and drop: [CodePen Example Link] (assuming that CodePen link should be inserted here).

    As with the last example, remember that the generated content may have problems with accessibility.

  5. Use CSS filters to achieve frosted glass effect

    With the release of iOS 7, Apple brings us a “frosted glass” effect—transparent, blurry elements that look like frosted glass windows. Inspired by Apple's implementation, this effect began to appear in many places. Reproducing this effect is a bit tricky before you have a CSS filter, you have to use a blurred image to create a frosted glass effect. Now, almost all major browsers fully support CSS filters, so it's much easier to reproduce this effect. [Can I Use css-filters?](assuming that Can I Use link should be inserted here)

    In the future, we can use the

    and

    functions to create similar effects, but these two functions are currently supported only by Safari. backdrop-filter filter()

  6. Use HTML elements as background image

    Usually, you specify a JPEG or PNG file as the background image, or maybe a gradient. But did you know that using the

    function, you can also use

    as the background image? Currently, the element() function is only supported by Firefox: [Can I Use css-element-function?] (assuming that the Can I Use link should be inserted here) <div> <code>element()The possibilities are almost limitless, here is an example from MDN.

  7. Create smarter grids with calc()

    Fluid mesh is a great thing, but there are some serious problems. For example, it is not possible to make the spacing between the top and the bottom the same size as the spacing between the left and right. Also, the marking is very confusing, depending on the grid system you are using. Even flexbox itself is not the final solution, but using the

    function (which can be used as a value in CSS), the grid can get better. In this tutorial on this website, George Martsoukos shows some practical examples, such as a gallery grid with perfect spacing. Using CSS preprocessors like Sass, building creative mesh systems can be very simple and easy to maintain. Since browser support is almost perfect,

    is a convenient feature you should definitely use. [Can I Use calc?](assuming that Can I Use link should be inserted here)calc() calc()

  8. Use CSS calc() to align position:fixed elements

    Another use case for a function is to align elements with fixed positions. For example, if you have a content wrapper on the left and right with fluid spacing, and you want to precisely align the fixed elements inside that wrapper - you will have a hard time determining the "right" or "left" attribute selection Which value? With

    , you can combine relative and absolute values ​​to align elements perfectly: calc() calc()

    This is an example: [CodePen example link] (assuming that CodePen link should be inserted here)
    .tooltip::after {
      content: attr(data-tooltip);
    }

  9. Animate with cubic-bezier()

    To make the UI of a website or application more attractive, you can use animations, but the standard easing options are very limited. For example, "linear" or "ease-in-out". Something like bouncing animation is not possible even with standard options. Using the

    function, you can animate elements exactly as you wish.

    cubic-bezier() There are two ways to use

    - understand the math behind it and build it yourself, or use the

    generator. cubic-bezier() cubic-bezierHonestly, I will choose the latter.

  10. Conclusion

    Skillful use of CSS functions not only solves known problems (such as building a smarter grid system), but also provides you with greater creative freedom. As browser support gets better, you should carefully look at your CSS and improve it using functions like

    .

    calc()

    Frequently Asked Questions about CSS Functions

    As a beginner, what basic CSS functions should I understand?

    CSS function is used to set the value of the CSS attribute. Some basic functions that every beginner should know include

    ,

    , rgb(), rgba(), hsl(), and hsla(). The calc() and rgb() functions are used to define colors, while the rgba() and hsl() functions are used to define colors based on hue, saturation, and brightness. The hsla() function allows you to perform calculations to determine the CSS attribute value. calc()

    How to use the calc() function in CSS?

    The

    function in

    in CSS is used to perform calculations that can be used as attribute values. This function can use the " " (addition), "-" (subtraction), "*" (multiple), and "/" (division) mathematical operators. For example, you can use calc() to create a div that always minus 20 pixels for viewport width 50% as shown below: calc(). div { width: calc(50% – 20px); }

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

    The main difference between the

    and

    functions in rgb()CSS is that rgba() contains an alpha channel that 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 translucent red, you can use: rgba(). color: rgba(255, 0, 0, 0.5);

    How to create gradients using CSS functions?

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

    Can I convert elements using CSS functions?

    Yes, CSS functions can be used to convert elements. The transform attribute can be used with various functions such as 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

    function in attr() in CSS is used to return the attribute value of the selected element. This is useful for generating content, etc. For example, you can use attr() to display the value of the link's "href" property in the tooltip: a:after { content: attr(href); }.

    How to 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 CSS as follows: color: var(--main-color);.

    Can I create animations using CSS functions?

    Yes, CSS functions can be used to create animations. The animation attribute in CSS is abbreviated attribute for eight different attributes, including animation-name, animation-duration, animation-timing-function, etc. For example, to create a 2-second animation called "slidein", you can use: animation: slidein 2s;.

    What is the purpose of the

    url() function in CSS?

    The

    function in url() in CSS is used to include files. The most common use of functions is to link to external stylesheets or include images. For example, to set the background image of an element, you can use: url(). background-image: url('image.jpg');

    Can I create 3D transformations using CSS functions?

    Yes, the CSS function can be used to create 3D transformations. The

    attribute in CSS can be used with functions such as transform, 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);.

    Please note that I have tried my best to pseudo-originalize the original text and preserve the original format and location of the image. Since I cannot access the CodePen and Can I Use websites, I replaced the related link with placeholders. Please find and insert the correct link yourself.

The above is the detailed content of 8 Clever Tricks with CSS Functions. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

Revisiting Image MapsRevisiting Image MapsMay 07, 2025 am 09:40 AM

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements.

State of Devs: A Survey for Every DeveloperState of Devs: A Survey for Every DeveloperMay 07, 2025 am 09:30 AM

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more. 

What is CSS Grid?What is CSS Grid?Apr 30, 2025 pm 03:21 PM

CSS Grid is a powerful tool for creating complex, responsive web layouts. It simplifies design, improves accessibility, and offers more control than older methods.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment