CSS Classes and IDs are attributes used to target and style specific HTML elements within a web page.
CSS Classes and IDs
- Classes are used to group elements with similar characteristics and apply styles to them collectively.
- You can assign multiple classes to an element by separating them with spaces in the class attribute.
- In CSS, classes are denoted using a dot (.) followed by the class name.
- Classes are versatile and can be reused across different elements.
- You can select elements by class in CSS using the class selector (e.g., .class-name).
- IDs are used to uniquely identify a specific element within a web page.
- Each element can have only one ID, and it must be unique within the entire HTML document.
- In CSS, IDs are denoted using a hash (#) followed by the ID name.
- IDs are typically used to style individual elements or target them with JavaScript.
- You can select elements by ID in CSS using the ID selector (e.g., #id-name).
Both CSS classes and IDs are essential for targeting specific elements and applying custom styles or behavior to them. Classes provide flexibility for styling groups of elements, while IDs allow for precise targeting of individual elements within a page. It's important to use them appropriately and adhere to best practices to maintain a well-structured and maintainable codebase.
CSS Classes
- Step 1 : Open the html editor ,Identify the elements you want to assign a class to. Let's consider a group of <p> elements.
- Step 2 :In your HTML markup ( html code ), add the class attribute to each element with the desired class name. Step 3 :In the CSS code area, use the class selector (.) followed by the class name to target the elements.
For example:
<p class="highlight">This is a paragraph.</p>
<p class="highlight">This is another paragraph.</p>
.highlight {
color: red;
font-weight: bold;
}
- Step 4 : Paste the css style to your HTML document.
- Result : The <p> elements with the class "highlight" will have their text color set to red and their font weight set to bold.
This is a paragraph.
This is another paragraph.
CSS IDs
- Step 1 : In the html editor , Identify the element you want to assign an ID to. Let's choose a <div> container.
- Step 2 : In your HTML markup, add the id attribute to the element with the desired ID name.
- Step 3 : In the CSS code area, use the ID selector (#) followed by the ID name to target the element.
For example:
<div id="header">This is the header</div>
#header {
background-color: blue;
color: white;
}
- Step 4 : Paste the css style or apply the <style> tag to your HTML document.
- Result : The <div> element with the ID "header" will have a blue background color and white text color.
This is the header
×