Functions, Variables, Pseudo-Selectors, Transform and Transition, and Animations

Syed Aquib AliSyed Aquib Ali
13 min read

Functions

Math Functions

CSS math functions calc(), min(), and max() are powerful tools for performing calculations directly within your stylesheets, allowing for more flexible and dynamic styling. Here’s an in-depth explanation of each function:

  1. calc()

The calc() function allows you to perform basic calculations to determine CSS property values. It can handle addition (+), subtraction (-), multiplication (*), and division (/).

#div1 {
    width: calc(100% - 50px);
}
#div2 {
    margin: calc(1em + 10px);
}
#div3 {
    height: calc(100vh / 2);
}
  • calc() is useful when you need to combine different units or dynamically adjust sizes. For instance, you might want a div to be full width minus a fixed margin or padding.
  1. min()

The min() function returns the smallest (most negative) value from a comma-separated list of values. This function is particularly useful for setting responsive properties where you want to ensure a value doesn’t exceed a certain limit.

div {
    width: min(100%, 500px);
}
h3 {
    font-size: min(4vw, 20px);
}
  • min() helps in creating responsive designs by capping a value. For example, it ensures that a container doesn't grow larger than a specified maximum value.
  1. max()

The max() function returns the largest (most positive) value from a comma-separated list of values. This is useful for ensuring a minimum size or value.

div {
    width: max(300px, 50%);
}
h3 {
    font-size: max(2vw, 16px);
}
  • max() ensures that a value doesn't drop below a certain threshold, which is useful for maintaining readability or usability across different screen sizes.

Combining calc(), min(), and max():

.container {
    width: min(max(300px, 50%), calc(100% - 40px));
}
  • The width will be at least 300px.

  • It will take up 50% of the available width if that is larger than 300px.

  • It will never exceed 100% of the available width minus 40px.

Variables

In CSS, global variables (also known as CSS custom properties) allow you to define reusable values that can be referenced throughout your stylesheet. This is particularly useful for maintaining consistent styling and making global updates more manageable.

  1. Defining Global Variables

Global variables are usually defined within the :root pseudo-class, which represents the top-level element of the document. Variables are prefixed with --.

:root {
    --black-text: #000000;
}
  1. Using Global Variables

To use a global variable, you reference it with the var() function.

h1 {
    color: var(--black-text);
}
/* All of the h1's on your HTML will have a black color that is defined in the global variable. */

Benefits of Using Global Variables

  1. Consistency:

    • By defining a color, font size, spacing value, etc., in one place, you ensure that the same value is used consistently throughout your stylesheet.
  2. Ease of Maintenance:

    • If you need to update a value (e.g., changing a primary color), you only have to update the variable definition, rather than searching through the entire stylesheet.
  3. Readability:

    • Variables can make your CSS more readable by giving meaningful names to values.
  4. Dynamic Styling:

    • Variables can be modified using JavaScript, enabling dynamic styling changes.

Example using a global/root variable

:root {
    --black-text: #000000;
    --primary-color: #3498db;
    --padding: 20px;
    --font-size: 16px;
}

body {
    font-size: var(--font-size);
    color: var(--black-text);
}

h1 {
    color: var(--primary-color);
    padding: var(--padding);
}

p {
    margin-bottom: var(--padding);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Variables Example</title>
</head>
<body>
    <h1>Heading 1</h1>
    <p>This is a paragraph with some text.</p>
    <p>Another paragraph to demonstrate spacing.</p>
</body>
</html>
  • Initially, --primary-color is set to #3498db.

  • When the button is clicked, JavaScript changes --primary-color to #e74c3c, which updates the color of the <h1> element dynamically.

  1. Defining Local Variables

Local variables are defined and used in the same way as global variables but are only available within the scope of the selector in which they are defined.

h1 {
    --white-text: #ffffff; /* Define a local variable */
    color: var(--white-text); /* Use the local variable */
}
  • The variable --white-text is defined locally within the h1 selector.

  • The color property of h1 elements is set to the value of the local --white-text variable.

Example using a global/root variable

/* Global variable */
:root {
    --global-color: #000000;
}

body {
    color: var(--global-color);
    background-color: #f0f0f0;
}

/* Local variable in h1 */
h1 {
    --white-text: #ffffff;
    color: var(--white-text);
    background-color: #333333;
    padding: 10px;
}

/* Another local variable in p */
p {
    --paragraph-color: #ff5733;
    color: var(--paragraph-color);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Local Variables Example</title>
</head>
<body>
    <h1>This is a heading</h1>
    <p>This is a paragraph with a different color.</p>
</body>
</html>
  1. Global Variable:

    • --global-color is defined in the :root and can be used throughout the document.

    • The body uses --global-color for its text color.

  2. Local Variable in h1:

    • --white-text is defined within the h1 selector.

    • This variable is only available within the scope of h1.

    • The h1 elements use --white-text for their color.

  3. Local Variable in p:

    • --paragraph-color is defined within the p selector.

    • This variable is only available within the scope of p.

    • The p elements use --paragraph-color for their color.

Example with override

:root {
    --text-color: #000000; /* Global variable */
}

body {
    color: var(--text-color); /* Uses the global variable */
}

h1 {
    --text-color: #ffffff; /* Local variable that overrides the global one */
    color: var(--text-color); /* Uses the local variable */
}

Using CSS variables improves the maintainability, readability, and flexibility of your CSS. It allows for a centralized way to manage and update values that are reused throughout your stylesheets.

Pseudo-Classes

Pseudo-classes in CSS are used to define the special states of an element. They enable the application of styles based on an element's state or its relation to other elements, without needing to alter the document's structure.

  1. :visited

The :visited pseudo-class targets links that the user has already visited. This helps in visually distinguishing between links that have been clicked and those that have not.

a:visited {
    color: purple; /* Example style for visited links */
}
  • Privacy Consideration: Due to privacy concerns, modern browsers restrict the styles that can be applied using :visited. Only certain properties like color, background-color, border-color, outline-color, and column-rule-color can be used.
  1. :hover

The :hover pseudo-class applies styles to an element when the user hovers over it with a pointing device, such as a mouse.

button:hover {
    background-color: blue; /* Example style for button on hover */
}
  • Interactive Elements: Commonly used to enhance the interactivity of buttons, links, and other UI components by providing visual feedback.
  1. :first-child

The :first-child pseudo-class targets an element that is the first child of its parent.

p:first-child {
    font-weight: bold; /* Example style for the first child paragraph */
}
  • Child Selector: Specifies to select the first child.
  1. :last-child

The :last-child pseudo-class targets an element that is the last child of its parent.

p:last-child {
    margin-bottom: 0; /* Example style for the last child paragraph */
}
  • Child Selector: Specifies to select the last child.
  1. :nth-child()

The :nth-child() pseudo-class targets elements based on their position in a parent element. It accepts a formula or keyword to select elements.

/* Using a formula */
li:nth-child(2n) {
    background-color: lightgray; /* Example style for every 2nd list item */
}

/* Using a specific number */
li:nth-child(3) {
    color: red; /* Example style for the 3rd list item */
}
  • Flexible Styling: Allows for more complex selections, such as styling every 2nd element (:nth-child(2n)), every 3rd element (:nth-child(3n)), or elements at specific positions within a parent, such as 4th element (:nth-child(4)).

Example using pseudo-class

 /* Visited link */
a:visited {
    color: purple;
}

/* Hover effect */
button:hover {
    background-color: blue;
    color: white;
}

/* First child */
p:first-child {
    font-weight: bold;
}

/* Last child */
p:last-child {
    margin-bottom: 0;
}

/* Nth child (every 2nd list item) */
li:nth-child(2n) {
    background-color: lightgray;
}

/* Nth child (specific item, 3rd list item) */
li:nth-child(3) {
    color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pseudo-classes Example</title>
</head>
<body>
    <a href="https://example.com">Visit Example</a>
    <button>Hover over me</button>
    <div>
        <p>First paragraph</p>
        <p>Second paragraph</p>
        <p>Third paragraph</p>
    </div>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
        <li>Item 5</li>
    </ul>
</body>
</html>
  • :visited: The link to "https://example.com" will turn purple after being visited.

  • :hover: The button changes its background color to blue and text color to white when hovered over.

  • :first-child: The first paragraph within its parent div is bold.

  • :last-child: The last paragraph has no bottom margin.

  • :nth-child(2n): Every 2nd list item has a light gray background.

  • :nth-child(3): The third list item has red text.

Pseudo-Elements

Pseudo-elements in CSS are used to style specific parts of an element, such as the first letter, the first line, or to insert content before or after the element's content. They are denoted by a double colon (::) to distinguish them from pseudo-classes. However, some older browsers also support the single colon syntax (:).

  1. ::first-letter

The ::first-letter pseudo-element applies styles to the first letter of the first line of a block-level element.

p::first-letter {
    font-size: 2em;
    font-weight: bold;
    color: red;
}
  • The first letter of the paragraph will be twice as large, bold, and red.
  1. ::first-line

The ::first-line pseudo-element applies styles to the first line of a block-level element. The length of the first line depends on the width of the containing block and other styling factors.

p::first-line {
    font-weight: bold;
    color: blue;
}
  • The first line of the paragraph will be bold and blue.
  1. ::before

The ::before pseudo-element inserts content before the content of the selected element. This pseudo-element is often used to add decorative content or icons.

h1::before {
    content: "★ ";
    color: gold;
}
  • The content is a must to write property while using ::before, even if you don't want to put any content before the element.

  • A gold star will appear before the text "Important Heading" in the h1 element.

  1. ::after

The ::after pseudo-element inserts content after the content of the selected element. Like ::before, it is used for adding decorative content.

h1::after {
    content: " ★"; /* Example style */
    color: gold;
}
  • Just like in ::before it was must to write property, it applies the same here as well.

  • A gold star will appear after the text "Important Heading" in the h1 element.

Transforms

The transform property in CSS is used to apply various transformations to an element. These transformations can be used to translate (move), scale (resize), rotate, and skew (distort) elements. Transformations can be 2D or 3D, allowing for a wide range of visual effects.

div {
    transform: scale(1.2) rotate(30deg);
}
  • Transform is a shorthand for using scale(), skew(), translate() and rotate() properties at ones.

Here's how you can use these properties individually:

  1. scale(): Resizes the element. The function can take one or two values.

    • scale(2): Uniformly scales the element by 2x in both the X and Y directions.

    • scale(2, 1): Scales the element by 2x in the X direction and 1x in the Y direction.

.element {
    transform: scale(1.5); /* Uniform scaling */
    transform: scale(1.5, 2); /* Non-uniform scaling */
}
  1. skewX(): Skews the element along the X-axis by a specified angle.
.element {
    transform: skewX(20deg);
}
  1. skewY(): Skews the element along the Y-axis by a specified angle.
.element {
    transform: skewY(20deg);
}
  1. translate(): Moves the element from its current position. The function can take one or two values.

    • translate(tx): Moves the element tx pixels along the X-axis.

    • translate(tx, ty): Moves the element tx pixels along the X-axis and ty pixels along the Y-axis.

    .element {
        transform: translate(50px); /* Moves 50px to the right */
        transform: translate(50px, 20px); /* Moves 50px to the right and 20px down */
    }
  1. rotate(): Rotates the element clockwise by a specified angle (in degrees).
.element {
    transform: rotate(45deg);
}
  1. rotate(): Rotates the element clockwise by a specified angle (in degrees).
.element {
    transform: rotate(45deg);
}

3D Transform Functions

  1. rotateX(): Rotates the element around the X-axis.
.element {
    transform: rotateX(45deg);
}
  1. rotateY(): Rotates the element around the Y-axis.
.element {
    transform: rotateY(45deg);
}

Example using Transform properties

.box {
    width: 100px;
    height: 100px;
    background-color: lightblue;
    margin: 20px;
    display: inline-block;
    }

.scale {
    transform: scale(1.5);
}

.skewX {
    transform: skewX(20deg);
}

.skewY {
    transform: skewY(20deg);
}

.translate {
transform: translate(50px, 20px);
}

.rotate {    
    transform: rotate(45deg);
}

.rotateX {
    transform: perspective(200px) rotateX(45deg);
}

.rotateY {
transform: perspective(200px) rotateY(45deg);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Transform Example</title>
</head>
<body>
    <div class="box scale">Scale</div>
    <div class="box skewX">SkewX</div>
    <div class="box skewY">SkewY</div>
    <div class="box translate">Translate</div>
    <div class="box rotate">Rotate</div>
    <div class="box rotateX">RotateX</div>
    <div class="box rotateY">RotateY</div>
</body>
</html>
  • .scale: The box is scaled up to 1.5 times its original size.

  • .skewX: The box is skewed along the X-axis by 20 degrees.

  • .skewY: The box is skewed along the Y-axis by 20 degrees.

  • .translate: The box is moved 50 pixels to the right and 20 pixels down.

  • .rotate: The box is rotated 45 degrees clockwise.

  • .rotateX: The box is rotated around the X-axis by 45 degrees, creating a 3D effect.

  • .rotateY: The box is rotated around the Y-axis by 45 degrees, also creating a 3D effect.

The transform property is a powerful tool for creating dynamic and visually appealing effects on web pages. By understanding and utilizing these various transformation functions, you can greatly enhance the user experience and interactivity of your website.

Transition

CSS transition provide a way to animate changes to CSS properties, allowing for smooth and gradual shifts from one state to another. This can enhance the user experience by providing visual feedback and making interactions feel more responsive and dynamic.

selector {
    transition: background-color 2s ease-in-out 1s;
 /* transition: property duration timing-function delay; */
}
  • The transition property is a shorthand that allows you to define the transition effect in a single line.
  1. transition-property

This specifies the CSS property or properties to which the transition will be applied.

.element {
    transition-property: background-color;
}
  1. transition-duration

This specifies the duration over which the transition should occur. The value is defined in seconds (s) or milliseconds (ms).

.element {
    transition-duration: 2s;
}
  1. transition-timing-function

This specifies the speed curve of the transition effect. Common values include ease, linear, ease-in, ease-out, ease-in-out, and cubic-bezier(n,n,n,n).

.element {
    transition-timing-function: ease-in-out;
}
  1. transition-delay

This specifies the delay before the transition effect starts. The value is defined in seconds (s) or milliseconds (ms).

.element {
    transition-delay: 1s;
}
.element2 {
    transition-delay: 100ms;
}

Example using Transition properties

.box {
    width: 100px;
    height: 100px;
    background-color: lightblue;    
    transition-property: background-color, transform;
    transition-duration: 1s, 0.5s;
    transition-timing-function: ease-in-out, linear;
    transition-delay: 0.5s, 0s;
}

.box:hover {
    background-color: lightcoral;
    transform: rotate(45deg);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Transition Example</title>
</head>
<body>
    <div class="box"></div>
</body>
</html>
  1. Initial State (Non-Hovered)

    • The .box element has a width and height of 100px and a light blue background.

    • The transition properties are set for background-color and transform with different configurations.

  2. Transition Configuration

    • transition-property: background-color, transform;: Specifies that transitions should be applied to the background-color and transform properties.

    • transition-duration: 1s, 0.5s;: The transition for background-color will last 1 second, and for transform, it will last 0.5 seconds.

    • transition-timing-function: ease-in-out, linear;: The background-color transition will follow an ease-in-out curve, while the transform transition will follow a linear curve.

    • transition-delay: 0.5s, 0s;: The background-color transition will start after a 0.5-second delay, while the transform transition will start immediately.

  3. Hover State

    • When the .box is hovered over, its background-color changes to light coral, and it rotates 45 degrees.

    • The transitions defined earlier will smoothly animate these changes according to their respective properties, durations, timing functions, and delays.

Explanation about Timing Function:

  • ease: Starts slow, then fast, then ends slow.

  • linear: The transition has the same speed from start to end.

  • ease-in: Starts slow, then fast.

  • ease-out: Starts fast, then slow.

  • ease-in-out: Starts slow, becomes fast in the middle, and then ends slow.

  • cubic-bezier(n,n,n,n): Allows you to define your own timing function using cubic-bezier curves, giving you full control over the transition speed curve.

By using the transition you can create sophisticated animations that enhance user interaction and provide a smoother user experience. The flexibility of transitions allows for precise control over the animation effects, making it a powerful tool in CSS for creating engaging web designs.

0
Subscribe to my newsletter

Read articles from Syed Aquib Ali directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Syed Aquib Ali
Syed Aquib Ali

I am a MERN stack developer who has learnt everything yet trying to polish his skills 🥂, I love backend more than frontend.