CSS Selectors
CSS Selectors
Moiez Armoghan
Roll No:
231509
Subject:
Web Engineering
Assignment Topic:
Selectors In CSS And Their Demonstration
Teacher:
M Hashir
Introduction:
CSS selectors are patterns used to select and style elements in HTML. They define how specific
elements should appear based on their attributes, classes, IDs, or relationships.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Universal Selector</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Welcome</h1>
<p>This text should be blue and in Arial.</p>
</body>
</html>
CSS (styles.css):
*{
color: blue;
font-family: Arial, sans-serif;
}
OutPut:
2. Element Selector (p, h1, etc.)
The element selector targets all instances of a particular HTML tag.
HTML:
<p>This is a paragraph.</p>
<p>Another paragraph.</p>
CSS:
p{
font-size: 16px;
line-height: 1.5;
}
OutPut:
HTML:
<p class="highlight">This text is highlighted.</p>
CSS:
.highlight {
background-color: yellow;
font-weight: bold;
}
OutPut:
4. ID Selector (#)
The ID selector applies styles to a unique element with a specific ID.
HTML:
<h1 id="main-title">This is a heading</h1>
CSS:
#main-title {
font-size: 24px;
text-align: center;
}
HTML:
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
CSS:
h1, h2, h3 {
color: darkgreen;
}
OutPut:
6. Descendant Selector ( )
The descendant selector styles elements inside a specific parent element.
HTML:
<div>
<p>This paragraph inside div will be red.</p>
</div>
<p>This paragraph is outside the div.</p>
CSS:
div p {
color: red;
}
OutPut:
7. Child Selector (>)
The child selector only applies styles to direct children of an element.
HTML:
<ul>
<li>Item 1</li>
<li>Item 2</li>
<ul>
<li>Sub-item</li>
</ul>
</ul>
CSS:
ul > li {
list-style-type: square;
}
OutPut:
8. Attribute Selector ([attribute])
The attribute selector targets elements based on their attributes.
HTML:
<a href="https://example.com" target="_blank">External Link</a>
<a href="https://example.com">Normal Link</a>
CSS:
a[target="_blank"] {
color: red;
}
OutPut: