Understanding CSS Syntax and Selectors: A Beginner's Guide
Learn the fundamental syntax and selectors used in CSS (Cascading Style Sheets) for styling HTML elements. This tutorial covers basic CSS rules, selectors (element, class, ID), and how to apply styles to create visually appealing and functional web pages.
Understanding CSS Syntax and Selectors
CSS Structure: Selectors, Properties, and Values
CSS (Cascading Style Sheets) styles HTML elements. A CSS rule consists of three parts:
- Selector: An HTML tag (e.g., `p`, `div`, `h1`) or other element that the CSS rule will apply to. Selectors can be very specific (targeting particular elements or classes) or general (applying to all elements of a certain type).
- Property: A CSS attribute that controls an element's appearance (e.g., `color`, `font-size`, `background-color`, `border`). These properties correspond to attributes in HTML tags but are expressed differently in CSS.
- Value: The value assigned to a property, determining how the property is applied (e.g., `red`, `16px`, `#f0f0f0`, `solid`). Values can be keywords, numbers, lengths, colors, or other data types.
CSS Syntax
The basic syntax for a CSS rule is:
selector { property: value; }
Multiple properties can be defined within the curly braces, separated by semicolons.
Example: Basic CSS Styling
HTML
<div>
<h1 id="header">Hello, CSS Example!</h1>
<p>Welcome to javaTpoint. Here is a styled button:</p>
<button class="button">Click Me!</button>
</div>
CSS
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f0f0f0;
}
#header {
background-color: lightblue;
color: white;
text-align: center;
padding: 10px;
}
h1 {
font-size: 2em;
margin-bottom: 10px;
}
p {
font-size: 1em;
margin-bottom: 10px;
}
.button {
background-color: red;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
.button:hover {
background-color: darkred;
}
Types of CSS Selectors
CSS offers various types of selectors to target specific HTML elements:
1. Type Selectors
Select elements based on their tag name (e.g., h1, h2, h3 { color: blue; }
).
2. Universal Selectors
The universal selector (`*`) selects all elements on the page.
3. Descendant Selectors
Select child elements within a parent (e.g., div p { text-align: center; }
).
4. Class Selectors
Select elements with a specific class attribute (e.g., .myClass { font-size: 1.2em; }
).
5. ID Selectors
Select elements with a specific ID attribute (e.g., #myId { color: red; }
).
6. Child Selectors
Select elements that are direct children of a parent (e.g., ul > li { list-style: square; }
).
7. Attribute Selectors
Select elements based on their attributes (e.g., img[alt] { border: 1px solid black; }
selects images with an alt attribute).