June 3, 2024
CSS Variables
CSS variables, also known as custom properties, allow you to store values in a reusable way. They make it easier to manage and update styles across a website.
Example:
:root {
--primary-color: #ff5733;
--secondary-color: #33c1ff;
}
body {
color: var(--primary-color);
background-color: var(--secondary-color);
}
Pseudo-classes and Pseudo-elements
Pseudo-classes and pseudo-elements allow you to style elements based on their state or position in the document.
:hover
, :focus
, :nth-child
).a:hover {
color: red;
}
::before
, ::after
).p::first-line {
font-weight: bold;
}
p::before {
content: "Note: ";
color: red;
}
CSS Transitions
CSS transitions allow you to change property values smoothly over a given duration.
Example:
button {
background-color: #33c1ff;
transition: background-color 0.3s ease;
}
button
{
background-color: #ff5733;
}
CSS Animations
CSS animations allow you to animate the properties of an element over a sequence of keyframes.
Example:
@keyframes slidein {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
}
div {
animation: slidein 1s ease-in-out;
}
Exercise: Creating Interactive Web Elements
Let's create an interactive button and an animated banner using the techniques we've learned.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Elements</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button>Hover me</button>
<div class="banner">Welcome to My Website</div>
</body>
</html>
:root {
--primary-color: #33c1ff;
--secondary-color: #ff5733;
}
body {
font-family: Arial, sans-serif;
padding: 20px;
background-color: #f4f4f4;
}
button {
background-color: var(--primary-color);
color: white;
border: none;
padding: 10px 20px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button
{
background-color: var(--secondary-color);
}
.banner {
background-color: var(--primary-color);
color: white;
padding: 20px;
margin-top: 20px;
animation: slidein 1s ease-in-out;
}
@keyframes slidein {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
}
Open the HTML file in a browser to see your interactive button and animated banner. Experiment with different CSS variables, pseudo-classes, pseudo-elements, transitions, and animations to enhance the interactivity and visual appeal of your web elements.
Coming Up Next
In Chapter 11, we'll explore CSS preprocessors like SASS and LESS, which provide additional features and syntax for writing more efficient and maintainable CSS.
Please Sign In to post a comment.