Professional Documents
Culture Documents
In the above example, every child element under the DIV element is
styled.
Universal selector vs Body selector:
Universal selector:
• It selects and applies styles to all elements.
• It overrides default inherited properties of the
elements.
• Since it selects all the elements, its weight is
more.
Body selector:
• It selects and applies style only to BODY element.
• Many child elements(not all) inherit BODY element
properties and applies.
2. Class Selectors
Class selector is used to select CSS class applied HTML elements
to apply styles. Class selector starts with ‘.” followed by
name(ex: .section). This is one of the mostly used selector.
.section{
color:red;
position:relative;
left:50px;
}
.section-heading {
font-weight:bold;
}
3. ID Selectors
ID selector is used to select specified ID applied HTML element.
ID selector starts with ‘#” followed by name(ex: #section1). ID to
be unique to an HTML page.
#section-heading1 {
color: red;
}
#section-heading2 {
color: green;
}
4. Element Selectors
Element selector is used to select HTML elements based on element
type(ex: p, div).
p {
color:red;
}
In the above example, text color set to all P elements.
Note: If more than one CSS style declarations apply to the same
element then browser decides which specific CSS style declaration
to be applied to the element based on some predefined rules. This
is called Specificity.
In the above example, all P elements after DIV element are styled.
Adjacent Sibling(S1 + S2) vs General Sibling(S1 ~ S2) selectors:
• Adjacent sibling(S1 + S2) selector selects immediate
sibling element only but general sibling(S1 ~ S2)
selector selects all sibling elements of another
specified element. Both cases, both elements(S1 and
S2) should be in the same level.
[lang |= "fr"] {
color:red;
}
p:first-child {
border:1px solid red;
}
p:nth-child(2n+1){
border:1px solid red;
}
p:nth-last-child(even){
border:1px solid red;
}
In the above example, applicable even numbers are 2,4 and 6. But
2nd and 4th elements (selection order starts from bottom to top)
are not P elements and those are not styled. 6th element is a P
element and it is styled.
p:nth-of-type(2n+1){
border:1px solid red;
}
In the above example, 2n+1 formula values are 2*0+1=1, 2*1+1 = 3,
2*2+1 = 5. Here above order only applicable to P elements. So 1st,
3rd and 5th P elements are styled based on its type.
p:nth-last-of-type(2n+1){
border:1px solid red;
}
In the above example, 2n+1 formula values are 2*0+1=1, 2*1+1 = 3,
2*2+1 = 5. Here above order only applicable to P elements from
bottom to top. So 1sth and 3rd P elements(selection order starts
from bottom to top) are styled.
In the above example, unvisited <a> elements are styled (when page
first loads).