CSS element selectors allow you to target and style HTML elements based on their tag names.
The syntax for an element selector is simply the tag name itself, such as <div>, <p> or <h1>.
To target a specific element, use the element selector followed by curly braces {} to enclose the CSS rules.
Example
h1 {
color: blue;
font-size: 24px;
}
In this example, all <h1> elements on your web page will be styled with blue color and a font size of 24 pixels.
To target multiple elements, separate the element selectors with commas.
Example
h1, h2, h3 {
font-family: Arial, sans-serif;
font-weight: bold;
}
In this example, all <h1>, <h2> and <h3> elements will have the specified font family and font weight.
Element selectors can also be combined with other CSS selectors to target elements more precisely.
Example 1
<div class="container">
<h2>Title</h2>
<p>Content</p>
</div>
.container h2 {
color: red;
}
In this example, only the <h2> element within the container with the class "container" will have red text color.
Example 2Targeting a Specific Element within another Element
To target a specific element within another element, use a space to separate the element selectors.
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
ul li {
list-style-type: none;
}
In this example, all <li> elements within a <ul> element will have no bullet points.
CSS offers advanced element selectors that allow you to target elements based on their attributes, states, and relationships with other elements.
Example 1Targeting Elements with a Specific Attribute
To target elements with a specific attribute, use the attribute selector.
input[type="text"] {
border: 1px solid gray;
}
In this example, all <input> elements with the attribute type set to "text" will have a gray border.
Example 2Targeting Elements in a Specific State
To target elements in a specific state, such as hover or focus, use pseudo-classes.
a:hover {
color: red;
}
In this example, all <a> elements will have red text color when hovered over.