In CSS, a declaration is the core of styling, defining how an element should look. Each declaration consists of a property and a value.
Example 1: Setting Text Color
p {
color: blue; /* 'color' is the property, 'blue' is the value */
}
Explanation This example targets all <p>
(paragraph) elements and sets their text color to blue. The color
property specifies the foreground color, and blue
is the value assigned to it.
A property is a specific characteristic of an HTML element that you can style. There are hundreds of CSS properties, each controlling a different aspect of an element's appearance.
Example 2: Changing Font Size
h1 {
font-size: 24px; /* 'font-size' property controls text size */
}
Explanation Here, the font-size
property is used on <h1>
(heading 1) elements to make their text 24 pixels tall. This property is crucial for typographic control.
A value is the specific setting or attribute you assign to a CSS property. Values can be keywords, lengths, colors, URLs, or other data types, depending on the property.
Example 3: Adding Background Image
body {
background-image: url('images/background.jpg'); /* 'url()' function provides the image path */
}
Explanation This code sets a background image for the entire <body>
of the webpage. The url()
function specifies the path to the image file, demonstrating a functional value type.
Declarations are grouped into rule sets, targeting specific HTML elements using selectors. A semicolon ;
separates multiple declarations within a rule set.
Example 4: Multiple Declarations for a Button
.my-button {
background-color: green; /* Sets the background to green */
color: white; /* Sets the text color to white */
padding: 10px 20px; /* Adds internal spacing */
}
Explanation This example styles a button with the class my-button
. It applies three distinct declarations: background-color
, color
, and padding
, each separated by a semicolon.
Understanding CSS syntax, including declarations, properties, and values, is fundamental for front-end development and building responsive web designs. Mastering these core concepts unlocks powerful styling capabilities for web pages.
Example 5: Animating Opacity
.fade-in {
opacity: 0; /* Starts completely transparent */
transition: opacity 1s ease-in-out; /* Smooth transition over 1 second */
}
.fade-in:hover {
opacity: 1; /* Becomes fully opaque on hover */
}
Explanation This code creates a fade-in effect on an element with the class fade-in
. It manipulates the opacity
property from 0 to 1 over a 1-second transition
, a key feature in modern CSS animations.