In CSS, you can select HTML elements using various selectors, including ID selectors, class selectors, and attribute selectors. Here's how you can use each type of selector:
-
ID Selectors:
ID selectors target a specific HTML element with a unique ID attribute.
#myElement { /* Styles for the element with ID 'myElement' */ color: blue; }
In HTML:
<div id="myElement">This element is styled using an ID selector.</div>
-
Class Selectors:
Class selectors target elements with a specific class attribute.
.myClass { /* Styles for elements with class 'myClass' */ font-size: 16px; color: green; }
In HTML:
<p class="myClass">This paragraph is styled using a class selector.</p> <div class="myClass">This div is also styled using the same class selector.</div>
-
Attribute Selectors:
Attribute selectors target elements based on their attributes.
Selecting elements with a specific attribute:
[type="text"] { /* Styles for elements with attribute type="text" */ border: 1px solid #ccc; }
In HTML:
<input type="text" placeholder="Enter text here">
Selecting elements with a specific attribute and value:
[href^="https://"] { /* Styles for elements with href attribute starting with "https://" */ color: blue; }
In HTML:
<a href="https://example.com">Link to example.com</a>
Selecting elements with a specific attribute and containing a value:
[src*="image"] { /* Styles for elements with src attribute containing "image" */ width: 100px; height: 100px; }
In HTML:
<img src="image.jpg" alt="An image">
These are just a few examples of how you can use ID, class, and attribute selectors in CSS to target and style specific HTML elements. Combining these selectors allows you to create more complex and specific styles for your web page.