CSS syntax refers to the specific way we write code to style web pages using Cascading Style Sheets (CSS).
It defines how we tell the browser which elements on a webpage to target and what styles to apply to them.
CSS Syntax Basics
Selectors:
CSS selectors are used to target HTML elements that you want to style. They can be based on element types, classes, IDs, attributes, or even based on their relationship with other elements.
<style> /* Element selector */ p { font-size: 16px; color: #333; } /* Class selector */ .header { background-color: #f0f0f0; padding: 10px; } /* ID selector */ #main-content { border: 1px solid #ccc; } </style> <!-- HTML --> <div class="header"> <h1>Welcome to My Website</h1> </div> <div id="main-content"> <p>This is a paragraph with styled text.</p> </div>
Properties and Values:
CSS properties define the visual appearance of the selected elements, while values specify how these properties should be applied.
<style> /* Example of properties and values */ .button { background-color: #3498db; color: #fff; padding: 10px 20px; border-radius: 5px; text-decoration: none; } </style> <!-- HTML --> <body> <a href="#" class="button">Click Me</a> </body>
Declaration Blocks:
A declaration block is a group of CSS declarations within curly braces {}. Each declaration consists of a property and its corresponding value.
/* Declaration block example */ .card { width: 300px; background-color: #fff; border: 1px solid #ccc; padding: 15px; }
Comments
CSS supports comments for adding notes or explanations within your stylesheet, which are ignored by the browser.
/* This is a comment in CSS */ .footer { color: #999; font-size: 12px; }
Example HTML with CSS
Here’s a simple HTML example with embedded CSS:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sample Page</title> <style> /* Embedded CSS */ body { font-family: Arial, sans-serif; line-height: 1.6; } h1 { color: #333; } .container { max-width: 800px; margin: 0 auto; padding: 20px; } .button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; border-radius: 4px; } </style> </head> <body> <div class="container"> <h1>Welcome to Our Website</h1> <p>This is a sample paragraph. You can style me using CSS!</p> <a href="#" class="button">Click Me</a> </div> </body> </html>
- Selectors (
h1
,.container
,.button
) are used to target specific HTML elements. - Properties and Values (like
color
,font-size
,padding
) are applied to style those elements. - Declaration Blocks encapsulate multiple style rules within
{}
. - Comments (
/* Embedded CSS */
) provide explanations or notes within the CSS code.
CSS syntax is fundamental for web development as it defines the presentation and layout of web pages, making them visually appealing and user-friendly.