What is a CSS selector and what are its uses?
390
05-Jun-2024
Ravi Vishwakarma
05-Jun-2024A CSS selector is a pattern used to select and apply styles to specific elements in an HTML document. Selectors are a fundamental part of CSS, enabling you to target elements based on their type, class, ID, attributes, and more, to style them appropriately.
Types of CSS Selectors and Their Uses
Universal Selector (
*
)* { margin: 0; padding: 0; }
Type Selector (Element Selector)
p { color: blue; }
<p>
elements to have blue text.Class Selector
.header { font-size: 2em; }
header
.ID Selector
#main-content { padding: 20px; }
main-content
.Attribute Selector
[type="text"] { border: 1px solid #000; }
<input>
elements withtype="text"
.Descendant Selector
div p { color: green; }
<p>
elements that are within a<div>
.Child Selector
ul > li { list-style: none; }
<li>
elements that are direct children of a<ul>
.Adjacent Sibling Selector
h1 + p { margin-top: 0; }
<p>
element that immediately follows an<h1>
.General Sibling Selector
h1 ~ p { color: red; }
<p>
elements that are siblings of an<h1>
.Pseudo-Class Selector
a:hover { color: orange; }
<a>
element when the mouse hovers over it.Pseudo-Element Selector
p::first-line { font-weight: bold; }
<p>
elements.Example Usage
Benefits and Uses of CSS Selectors
By understanding and utilizing CSS selectors, you can create sophisticated and well-structured stylesheets that enhance the presentation and usability of your web pages.