Day 15: Css: Selector 1,2,3,4.
Selector 1
button{
background-color: aqua;
}
#primary{
background-color: brown;
}
p{
background-color: purple;
}
a[href="someone link"]{
background-color: red;
}
p,a{
background-color: orange;
}
-----------------------------------------------------------------------------------------------------------------------------
Selector 2
img+p{
}
div#id{
}
div.class1{
}
-----------------------------------------------------------------------------------------------------------------------------
Selector 3
ul li{
}
ul > li{
}
p ~ span{
}
-----------------------------------------------------------------------------------------------------------------------------
Child combinator / Direct child selector (>) in CSS
-It only matches elements that the second selector matches and are directly children of elements that the first selector matches.
-In the following example :
In the following example, only the paragraphs which are direct children of div with class name “parentDiv” are affected by applying the direct child selector (>), and only their font color will be changed to blue.
- Code :
<!DOCTYPE html>
<html>
<head>
<style>
.parentDiv{
background-color: aqua;
width: 500px;
height: 300px;
border: solid 5px black;
margin: 100px;
text-align: center;
}
.parentDiv > p{
color: blue;
}
</style>
</head>
<body>
<div class="parentDiv">
<p>This paragraph 1 is direct child of div</p>
<p>This paragraph 2 is direct child of div</p>
<div>
<p>This paragraph 3 is not a direct child of div as it is nested inside another div, hence it will not change into blue font color</p>
</div>
</div>
</body>
</html>
- Output :
What is the difference between direct child selector (.parent > .child) and Descendant combinator
(.parent .child)?
- Child combinator / Direct child selector (>) only matches elements that the second selector matches and are direct children of elements that the first selector matches, it does not select indirect children of the parent element.
- In Descendant combinator, all the elements that the second selector matches are selected, whether they are direct children or not.
- Example :
In the below given example, by using the Descendant combinator, all the paragraph tags are selected whether they are direct child or not. (unlike the direct child selector, where only direct child elements are selected)
Code :
<!DOCTYPE html>
<html>
<head>
<style>
.parentDiv{
background-color: aqua;
width: 500px;
height: 300px;
border: solid 5px black;
margin: 100px;
text-align: center;
}
.parentDiv p{
color: red;
}
</style>
</head>
<body>
<div class="parentDiv">
<p>This paragraph 1 is direct child of div</p>
<p>This paragraph 2 is direct child of div</p>
<div>
<p>This paragraph 3 is not a direct child of div</p>
</div>
</div>
</body>
</html>
- Output :
Comments
Post a Comment