CSS for Web Development

0% completed

Previous
Next
Create a Themeable Card Using CSS Variables

Problem Statement

  • Create a card component that uses CSS custom properties (variables) for its styling.
  • Define theme variables in the :root selector (e.g., background color, text color, border color, padding).
  • Apply these variables to style the card using the var() function.
  • Include a hover effect that changes the background color using one of the variables.
  • Ensure that changing the variables in one place can update the overall theme of the card.

Solution

HTML

. . . .

Explanation:

  • Variable Definition:

    • In the :root selector, several CSS custom properties (variables) are declared. These include variables for the card's background (--card-bg), text color (--card-text), border (--card-border), hover background (--card-hover-bg), and padding (--card-padding). This centralizes the theme settings.
  • Using CSS Variables:

    • Within the .card class, the var() function is used to apply the theme variables to properties like background-color, color, border, and padding. This ensures that the card's appearance is driven by the values defined in :root.
  • Hover Effect:

    • A hover effect is implemented on the .card using the rule .card:hover, which changes the background color to the value of --card-hover-bg with a smooth transition set by transition: background-color 0.3s ease;.
  • Benefits for Theming:

    • With this setup, updating the theme is as simple as modifying the values in the :root selector. For example, to switch to a dark theme, you could change --card-bg and --card-text to darker values, and the card’s appearance would update automatically.

This solution meets all the requirements by creating a flexible and themeable card component using CSS variables and the var() function.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next