The type selector in CSS is used to select HTML elements based on their tag name. For example, if you want to apply a style to all <p>
elements on a page, you would use the type selector p
. Here are some examples of how to use type selectors in CSS:
To apply a style to all elements of a specific type:
/* This will select all <p> elements and apply the style */
p {
color: blue;
font-size: 16px;
}
Type selectors can be combined with other selectors for more specific targeting:
/* Selects all <p> elements within a <div> */
div p {
color: green;
}
/* Selects all <a> elements with the class "external" */
a.external {
text-decoration: none;
color: red;
}
/* Selects all <ul> elements with a direct child <li> element */
ul > li {
list-style-type: none;
}
You can group multiple type selectors to apply the same style to different elements:
/* This will apply the same style to all <h1> and <h2> elements */
h1, h2 {
font-family: Arial, sans-serif;
margin-bottom: 10px;
}
Here is a complete example demonstrating the use of type selectors in a simple HTML document:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Type Selector Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<div>
<p>This is another paragraph inside a div.</p>
</div>
<a href="#" class="external">This is an external link</a>
</body>
</html>
styles.css
)/* Select all <h1> elements */
h1 {
color: navy;
}
/* Select all <p> elements */
p {
color: darkslategray;
font-size: 14px;
}
/* Select all <a> elements with class "external" */
a.external {
color: crimson;
text-decoration: underline;
}
In this example:
<h1>
elements will have the color navy.<p>
elements will have the color darkslategray and a font size of 14px.<a>
elements with the class external
will have the color crimson and an underline.