Understanding CSS Selector and Declarations

CSSWeb DevelopmentFront End Technology

CSS selectors are used to selecting HTML elements by matching each element of a given pattern. We define the styles by declaring property and their value inside the selector.

Syntax

The syntax for declaring styles is as follows −

Selector {
property: value; }

CSS has simple selectors, attribute selectors, pseudo-classes, pseudo-elements and a combination of selectors through standard combinators. The following table lists some of the selectors −

SelectorType of selectorDescription
*Universal selectorMatches all elements
eType selectorMatches all elements of type e
e1e2Descendant selectorMatches any e2 element that is a descendant of an e1 element.
e1>e2Child selectorMatches any e2 element that is a child of an element e1.
e[bar="demo"]Attribute selectorMatches any e element whose "bar" attribute value is exactly equal to "demo".
#idID selectorMatches element with ID equal to "id".

Example

The following examples illustrate CSS selectors −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
p::first-line {
   background-color: lightgreen;
   color: white;
   text-decoration: overline black;
}
</style>
</head>
<body>
<h2>Demo Heading</h2>
<p>This is our demo text. Only the first line will have a different style. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. </p>
</body>
</html>

Output

This gives the following output −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
p::first-line {
   background-color: lightgreen;
   color: white;
   text-decoration: overline red;
}
span {
   font-size: 1.4em;
}
#demo {
   box-shadow: inset 0 0 20px orange;
}
</style>
</head>
<body>
<h2>Student Details</h2>
<p><span>Student</span>details would be mentioned here. <span id="demo">Student Marks</span> includes the score of students in the final semester held July 2018. With that the ranks are also displayed.</p>
</body>
</html>

Output

This gives the following output −

raja
Published on 06-Jan-2020 10:56:20
Advertisements