SlideShare a Scribd company logo
CSS Inheritance &
Specificity
Sarah Hudson
What is specificity?
Answer:
1)How browsers
determine which CSS
properties to apply
to an element when
multiple,
conflicting rules
are given.
2)The weight given to
each ruleset,
determined by the
selectors given.
Is specificity different from inheritance?
Short answer, yes.
Inheritance refers to how child nodes inherit their parent
nodes’ styling, how styling cascades.
Specificity refers to how the browser determines which
styles to apply to an element.
Specificity can come into play in overriding inherited styles, but
child nodes don’t technically inherit the parents’ specificity rules
In other words -- You can use inheritance rules as guidelines
to write selectors, but don’t rely on the parents’
But why does this
matter? Anyone can
learn CSS in an hour
Anyone can learn & write CSS
quickly but understanding
specificity matters if:
You work on a large team
with many developers
You are pulled onto a
legacy project
You need to update a theme
(i.e., Shopify,
Wordpress, Squarespace)
You’re working on an open
source project
How do browsers decide what styles apply?
How browsers
work
● Networking layer opens
XHR requests to server
for docs and assets
● UI backend contains
default styles
● HTML and CSS are parsed
by the Rendering Engine
How browsers work, cont
● Rendering Engine: Will fetch files in 8KB chunks
● Content Tree: HTML and content parsed first
● Render Tree: Style attributes and CSS parsed, determines
the order of content
● Layout Tree: Node coordinates are calculated
● Paint: The browser’s UI Backend processes the information
from the trees and displays it on the screen
How browsers parse CSS
Browsers download CSS files as they’re linked and create
StyleSheet objects which contain rules
The browser traverses the DOM tree, and then traverses all
rulesets in CSS to match the values in class attributes
to selectors in rulesets
Browsers read selectors right to left; the last selector is
called the key selector
Making the decision, overview
Browsers take three things into account before applying CSS:
1.Source Order
a.Whichever ruleset comes last will be applied
2.Specificity
a.Whichever ruleset carries greater weight / more specific selectors
will be applied
3.Importance
a.Whichever ruleset is marked as being more important will be applied
Making the decision via specificity
The most specific selector: If more than one declaration
applies to the same element, then the most specific
selector wins
I.e., h2.headline will apply over .headline
This also works in overriding inherited styles, i.e., p > .red will
override p.
The most weighted selector: The selector that has the
highest specificity weight will win
I.e., #sidebar { … } weighs more than aside { … }
So how does specificity specifically work?
Specificity Weights
Built in rules assign weights to different selectors:
Tag selectors, pseudo-elements: 1 point
I.e., a { … }
Class selectors, attributes, pseudo-classes: 10 points
I.e., .headline { … }
ID selectors: 100 points
I.e., #sidebar
Two visuals of calculating specificity
1.Add the weights by 10s 2. Fill in the number of each
selector in its respective 1s, 10s,
etc space to determine the weight
Specificity Is Additive
The longer your selector is, the higher the specificity
weight is. Examples:
.sidebar li { … } = 10 + 1 = 11
.sidebar li a { … } = 10 + 1 + 1 = 12
#main-content .sidebar { … } = 100 + 10 = 110
#main-content .sidebar li { … } = 100 + 10 + 1 = 111
And so on...
Quick Exercise: How much weight is given?
1.div {}
a.Answer: 1 (1 tag element)
2.ul li {}
a. Answer: 2 (2 tag elements)
3.ul.special-links li a {}
a. Answer: 13 (3 tag elements and 1 class)
4.ul.special-links li a:hover {}
a. Answer: 23 (3 tag elements, 1 class, 1 pseudo-class)
That’s cool & all but can you show me some
code?
What ruleset will win? Example #1
<footer class=“main-footer”>
<a href=“#about-us”
class=“navigation--link site-map--
link”>About Us</a>
</footer>
.main-footer a { color: white }
a.site-map--link { color:
darkblue }
a { color: blue; }
a.navigation--link { color:
skyblue }
Answer: It’ll be sky blue because all the
selectors have the same weight, except for
the tag selector, and the navigation--link is
the last one
What ruleset will win? Example #2
<ul>
<li><a href=“#”>Home</a></li>
<li><a href=“#”>Contact</a></li>
</ul>
li > a { color: green; }
li a { color: brown; }
Answer: It will be brown because the
selectors are equal weight; it chooses the
last one. It’s important to note that
combinators such as > and ~ have no weight on
specificity. They’re a part of inheritance
instead, ensuring we only grab the a tags
directly under our li tags, but we don’t
apply the declarations to a tags which are in
divs in li elms
What ruleset will win? Example #3
What color will the links be give
this structure?
<aside id="sidebar">
<section id="salads">
<ul>
<li><a href="#">Cobb Salad</a></li>
</ul>
</section>
</aside>
aside#sidebar a {background-
color: yellow; }
aside#sidebar a[href="#"]
{background-color: lightgreen;}
section#salads li a {background-
color: aliceblue;}
Answer:The background will be light green.
This is because attribute selectors have a
specificity weight of 10, thus making it 1 +
100 + 1 + 10 = 112
What ruleset will win? Example #4
What color will the text be given
this structure?
<section id=“intro-text”>
<p>Lorem ipsum…</p>
</section>
section#intro-text {color: red
!important;}
p {color: darkgrey;}
Answer: Specificity is not inherited. Since
we’re using the parent element as a selector,
it will apply to the parent element, but
selecting “p” is more specific to the “p” tag
than the parent’s selector. Thus the
paragraph will be grey.
What ruleset will win? Example #5
What color will the text be given
this structure, where we apply
.orange-text on the last span?
Hint: We have 11 element selectors
in the first ruleset
html body main section header h2
div span span span span {color:
purple;}
.orange-text {color: orange;}
Answer: 11 beats 10, right? Well...if this
were simply math, but classes will always
beat out elements. That’s the tricky thing
about specificity. Each step up will always
beat out the step beneath it.
What ruleset will win? Example #6
<section>
<header>
<h2 style="color: red;"
class="test-important-
text">Test</h2>
</header>
</section>
style="color: red;"
.test-important-text {color:
purple !important;}
Answer: Inline styles are closer to the DOM,
so those should apply, right? In this case,
remember that !important breaks all
specificity rules. It is the only way to
override inline styles. So it will be purple.
What are some best practices?
Simplicity is best
Keep selectors as short and simple as possible to ensure that
stylesheets are:
Easily maintainable, readable, reusable, & intuitive
Easy to onboard (for new developers on the team)
Easy to come back to after months
Not chock full of convoluted rules tripping over each other
*** Use highly specific selectors as the exception, not the
rule, whenever possible
Use classes whenever possible
● Element selectors should mainly be used for resets, and
resets should mainly be done to level the browser playing
field
● Element selectors are too general and end up with adding
more rulesets for different styling/conditions
● Multiple resets mean that style rules were applied too
early and are usually the cause of specificity battles
● Classes are more semantic and provide specific intent
○ I.e., the selector .article-title instead of article > header > h2
More best CSS practices
● Rulesets should do one thing
○ I.e., .align-left should only float to the left; .slider should only
describe necessary items for slider component (no page layout, etc)
○ This allows you to reuse, mix and match
○ Follows modular approach the web is moving towards
○ Less issues with overwriting rules down the road
● Give classes semantic, intuitive names
○ I.e., .primary-brand-color is better than .dark-blue or using the
color throughout selectors
What are some anti-patterns?
Antipatterns, Pt. I
!important
Reasons:
Breaks specificity rules and is nearly impossible to override
Can result in bugs
Makes it difficult for developers / designers new to the project
IDs
Reasons:
IDs have a specificity weight of 100, making them difficult to
override and impossible to override with classes
Antipatterns, Pt. II
Long / unnecessarily specific selectors
Example: body .container .sidebar .links
Reasons:
Adds weight and causes slower processing / paint times as it has to
traverse the DOM to check for an exact match
Adds confusion in terms of readability / maintainability
Violates DRY
Qualified Selectors
FIN
Resources
Smashing Magazine -- CSS Specificity: Things You Should
Know
Mozilla’s Specificity Docs
Smashing Magazine -- CSS Specificity & Inheritance
How browsers work: Behind the scenes of modern web browsers
Specificity calculator
CSS Wizardry
Contact me
Email: sarah@sarah-
hudson.com
Twitter:
@SarahHudson2008
Website:
www.sarah-hudson.com

More Related Content

Similar to Charlotte FED - CSS Inheritance and Specificity

3-CSS_essentials introduction slides.ppt
3-CSS_essentials introduction slides.ppt3-CSS_essentials introduction slides.ppt
3-CSS_essentials introduction slides.ppt
Aasma13
 
3-CSS_essentials_developers_begineers.ppt
3-CSS_essentials_developers_begineers.ppt3-CSS_essentials_developers_begineers.ppt
3-CSS_essentials_developers_begineers.ppt
mohamed abd elrazek
 
3-CSS_essentials.ppt
3-CSS_essentials.ppt3-CSS_essentials.ppt
3-CSS_essentials.ppt
scet315
 
Css - Tutorial
Css - TutorialCss - Tutorial
Css - Tutorial
adelaticleanu
 
Css tutorial
Css tutorialCss tutorial
Css tutorial
Sohail Christoper
 
Shyam sunder Rajasthan Computer
Shyam sunder Rajasthan ComputerShyam sunder Rajasthan Computer
Shyam sunder Rajasthan Computer
shyamverma305
 
Dominate The Theme Layer
Dominate The Theme LayerDominate The Theme Layer
Dominate The Theme Layer
Jesper Wøldiche
 
Css tutorial by viveksingh698@gmail.com
Css tutorial by viveksingh698@gmail.comCss tutorial by viveksingh698@gmail.com
Css tutorial by viveksingh698@gmail.com
vivek698
 
Css tutorial
Css tutorialCss tutorial
Css tutorial
Edress Oryakhail
 
Css tutorial
Css tutorial Css tutorial
Css tutorial
Fakhrul Islam Talukder
 
Css tutorial
Css tutorialCss tutorial
Css tutorial
Mohamed Idris
 
Mdst3703 2013-09-12-semantic-html
Mdst3703 2013-09-12-semantic-htmlMdst3703 2013-09-12-semantic-html
Mdst3703 2013-09-12-semantic-html
Rafael Alvarado
 
Css Founder.com | Cssfounder org
Css Founder.com | Cssfounder orgCss Founder.com | Cssfounder org
Css Founder.com | Cssfounder org
Css Founder
 
Unit 2.1
Unit 2.1Unit 2.1
Unit 2.1
Unit 2.1Unit 2.1
CASCADING STYLE SHEETS (CSS).pptx
CASCADING STYLE SHEETS (CSS).pptxCASCADING STYLE SHEETS (CSS).pptx
CASCADING STYLE SHEETS (CSS).pptx
Asmr17
 
4. Web Technology CSS Basics-1
4. Web Technology CSS Basics-14. Web Technology CSS Basics-1
4. Web Technology CSS Basics-1
Jyoti Yadav
 
Lab#1 - Front End Development
Lab#1 - Front End DevelopmentLab#1 - Front End Development
Lab#1 - Front End Development
Walid Ashraf
 
Intro to CSS Selectors in Drupal
Intro to CSS Selectors in DrupalIntro to CSS Selectors in Drupal
Intro to CSS Selectors in Drupal
cgmonroe
 
Lec 1
Lec 1Lec 1

Similar to Charlotte FED - CSS Inheritance and Specificity (20)

3-CSS_essentials introduction slides.ppt
3-CSS_essentials introduction slides.ppt3-CSS_essentials introduction slides.ppt
3-CSS_essentials introduction slides.ppt
 
3-CSS_essentials_developers_begineers.ppt
3-CSS_essentials_developers_begineers.ppt3-CSS_essentials_developers_begineers.ppt
3-CSS_essentials_developers_begineers.ppt
 
3-CSS_essentials.ppt
3-CSS_essentials.ppt3-CSS_essentials.ppt
3-CSS_essentials.ppt
 
Css - Tutorial
Css - TutorialCss - Tutorial
Css - Tutorial
 
Css tutorial
Css tutorialCss tutorial
Css tutorial
 
Shyam sunder Rajasthan Computer
Shyam sunder Rajasthan ComputerShyam sunder Rajasthan Computer
Shyam sunder Rajasthan Computer
 
Dominate The Theme Layer
Dominate The Theme LayerDominate The Theme Layer
Dominate The Theme Layer
 
Css tutorial by viveksingh698@gmail.com
Css tutorial by viveksingh698@gmail.comCss tutorial by viveksingh698@gmail.com
Css tutorial by viveksingh698@gmail.com
 
Css tutorial
Css tutorialCss tutorial
Css tutorial
 
Css tutorial
Css tutorial Css tutorial
Css tutorial
 
Css tutorial
Css tutorialCss tutorial
Css tutorial
 
Mdst3703 2013-09-12-semantic-html
Mdst3703 2013-09-12-semantic-htmlMdst3703 2013-09-12-semantic-html
Mdst3703 2013-09-12-semantic-html
 
Css Founder.com | Cssfounder org
Css Founder.com | Cssfounder orgCss Founder.com | Cssfounder org
Css Founder.com | Cssfounder org
 
Unit 2.1
Unit 2.1Unit 2.1
Unit 2.1
 
Unit 2.1
Unit 2.1Unit 2.1
Unit 2.1
 
CASCADING STYLE SHEETS (CSS).pptx
CASCADING STYLE SHEETS (CSS).pptxCASCADING STYLE SHEETS (CSS).pptx
CASCADING STYLE SHEETS (CSS).pptx
 
4. Web Technology CSS Basics-1
4. Web Technology CSS Basics-14. Web Technology CSS Basics-1
4. Web Technology CSS Basics-1
 
Lab#1 - Front End Development
Lab#1 - Front End DevelopmentLab#1 - Front End Development
Lab#1 - Front End Development
 
Intro to CSS Selectors in Drupal
Intro to CSS Selectors in DrupalIntro to CSS Selectors in Drupal
Intro to CSS Selectors in Drupal
 
Lec 1
Lec 1Lec 1
Lec 1
 

Recently uploaded

DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
Quarter 3 SLRP grade 9.. gshajsbhhaheabh
Quarter 3 SLRP grade 9.. gshajsbhhaheabhQuarter 3 SLRP grade 9.. gshajsbhhaheabh
Quarter 3 SLRP grade 9.. gshajsbhhaheabh
aisafed42
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
Peter Muessig
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
Severalnines
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
Reetu63
 

Recently uploaded (20)

DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
Quarter 3 SLRP grade 9.. gshajsbhhaheabh
Quarter 3 SLRP grade 9.. gshajsbhhaheabhQuarter 3 SLRP grade 9.. gshajsbhhaheabh
Quarter 3 SLRP grade 9.. gshajsbhhaheabh
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
 

Charlotte FED - CSS Inheritance and Specificity

  • 3. Answer: 1)How browsers determine which CSS properties to apply to an element when multiple, conflicting rules are given. 2)The weight given to each ruleset, determined by the selectors given.
  • 4. Is specificity different from inheritance? Short answer, yes. Inheritance refers to how child nodes inherit their parent nodes’ styling, how styling cascades. Specificity refers to how the browser determines which styles to apply to an element. Specificity can come into play in overriding inherited styles, but child nodes don’t technically inherit the parents’ specificity rules In other words -- You can use inheritance rules as guidelines to write selectors, but don’t rely on the parents’
  • 5. But why does this matter? Anyone can learn CSS in an hour Anyone can learn & write CSS quickly but understanding specificity matters if: You work on a large team with many developers You are pulled onto a legacy project You need to update a theme (i.e., Shopify, Wordpress, Squarespace) You’re working on an open source project
  • 6. How do browsers decide what styles apply?
  • 7. How browsers work ● Networking layer opens XHR requests to server for docs and assets ● UI backend contains default styles ● HTML and CSS are parsed by the Rendering Engine
  • 8. How browsers work, cont ● Rendering Engine: Will fetch files in 8KB chunks ● Content Tree: HTML and content parsed first ● Render Tree: Style attributes and CSS parsed, determines the order of content ● Layout Tree: Node coordinates are calculated ● Paint: The browser’s UI Backend processes the information from the trees and displays it on the screen
  • 9. How browsers parse CSS Browsers download CSS files as they’re linked and create StyleSheet objects which contain rules The browser traverses the DOM tree, and then traverses all rulesets in CSS to match the values in class attributes to selectors in rulesets Browsers read selectors right to left; the last selector is called the key selector
  • 10. Making the decision, overview Browsers take three things into account before applying CSS: 1.Source Order a.Whichever ruleset comes last will be applied 2.Specificity a.Whichever ruleset carries greater weight / more specific selectors will be applied 3.Importance a.Whichever ruleset is marked as being more important will be applied
  • 11. Making the decision via specificity The most specific selector: If more than one declaration applies to the same element, then the most specific selector wins I.e., h2.headline will apply over .headline This also works in overriding inherited styles, i.e., p > .red will override p. The most weighted selector: The selector that has the highest specificity weight will win I.e., #sidebar { … } weighs more than aside { … }
  • 12. So how does specificity specifically work?
  • 13. Specificity Weights Built in rules assign weights to different selectors: Tag selectors, pseudo-elements: 1 point I.e., a { … } Class selectors, attributes, pseudo-classes: 10 points I.e., .headline { … } ID selectors: 100 points I.e., #sidebar
  • 14. Two visuals of calculating specificity 1.Add the weights by 10s 2. Fill in the number of each selector in its respective 1s, 10s, etc space to determine the weight
  • 15. Specificity Is Additive The longer your selector is, the higher the specificity weight is. Examples: .sidebar li { … } = 10 + 1 = 11 .sidebar li a { … } = 10 + 1 + 1 = 12 #main-content .sidebar { … } = 100 + 10 = 110 #main-content .sidebar li { … } = 100 + 10 + 1 = 111 And so on...
  • 16.
  • 17. Quick Exercise: How much weight is given? 1.div {} a.Answer: 1 (1 tag element) 2.ul li {} a. Answer: 2 (2 tag elements) 3.ul.special-links li a {} a. Answer: 13 (3 tag elements and 1 class) 4.ul.special-links li a:hover {} a. Answer: 23 (3 tag elements, 1 class, 1 pseudo-class)
  • 18. That’s cool & all but can you show me some code?
  • 19. What ruleset will win? Example #1 <footer class=“main-footer”> <a href=“#about-us” class=“navigation--link site-map-- link”>About Us</a> </footer> .main-footer a { color: white } a.site-map--link { color: darkblue } a { color: blue; } a.navigation--link { color: skyblue } Answer: It’ll be sky blue because all the selectors have the same weight, except for the tag selector, and the navigation--link is the last one
  • 20. What ruleset will win? Example #2 <ul> <li><a href=“#”>Home</a></li> <li><a href=“#”>Contact</a></li> </ul> li > a { color: green; } li a { color: brown; } Answer: It will be brown because the selectors are equal weight; it chooses the last one. It’s important to note that combinators such as > and ~ have no weight on specificity. They’re a part of inheritance instead, ensuring we only grab the a tags directly under our li tags, but we don’t apply the declarations to a tags which are in divs in li elms
  • 21. What ruleset will win? Example #3 What color will the links be give this structure? <aside id="sidebar"> <section id="salads"> <ul> <li><a href="#">Cobb Salad</a></li> </ul> </section> </aside> aside#sidebar a {background- color: yellow; } aside#sidebar a[href="#"] {background-color: lightgreen;} section#salads li a {background- color: aliceblue;} Answer:The background will be light green. This is because attribute selectors have a specificity weight of 10, thus making it 1 + 100 + 1 + 10 = 112
  • 22. What ruleset will win? Example #4 What color will the text be given this structure? <section id=“intro-text”> <p>Lorem ipsum…</p> </section> section#intro-text {color: red !important;} p {color: darkgrey;} Answer: Specificity is not inherited. Since we’re using the parent element as a selector, it will apply to the parent element, but selecting “p” is more specific to the “p” tag than the parent’s selector. Thus the paragraph will be grey.
  • 23. What ruleset will win? Example #5 What color will the text be given this structure, where we apply .orange-text on the last span? Hint: We have 11 element selectors in the first ruleset html body main section header h2 div span span span span {color: purple;} .orange-text {color: orange;} Answer: 11 beats 10, right? Well...if this were simply math, but classes will always beat out elements. That’s the tricky thing about specificity. Each step up will always beat out the step beneath it.
  • 24. What ruleset will win? Example #6 <section> <header> <h2 style="color: red;" class="test-important- text">Test</h2> </header> </section> style="color: red;" .test-important-text {color: purple !important;} Answer: Inline styles are closer to the DOM, so those should apply, right? In this case, remember that !important breaks all specificity rules. It is the only way to override inline styles. So it will be purple.
  • 25. What are some best practices?
  • 26. Simplicity is best Keep selectors as short and simple as possible to ensure that stylesheets are: Easily maintainable, readable, reusable, & intuitive Easy to onboard (for new developers on the team) Easy to come back to after months Not chock full of convoluted rules tripping over each other *** Use highly specific selectors as the exception, not the rule, whenever possible
  • 27. Use classes whenever possible ● Element selectors should mainly be used for resets, and resets should mainly be done to level the browser playing field ● Element selectors are too general and end up with adding more rulesets for different styling/conditions ● Multiple resets mean that style rules were applied too early and are usually the cause of specificity battles ● Classes are more semantic and provide specific intent ○ I.e., the selector .article-title instead of article > header > h2
  • 28. More best CSS practices ● Rulesets should do one thing ○ I.e., .align-left should only float to the left; .slider should only describe necessary items for slider component (no page layout, etc) ○ This allows you to reuse, mix and match ○ Follows modular approach the web is moving towards ○ Less issues with overwriting rules down the road ● Give classes semantic, intuitive names ○ I.e., .primary-brand-color is better than .dark-blue or using the color throughout selectors
  • 29. What are some anti-patterns?
  • 30. Antipatterns, Pt. I !important Reasons: Breaks specificity rules and is nearly impossible to override Can result in bugs Makes it difficult for developers / designers new to the project IDs Reasons: IDs have a specificity weight of 100, making them difficult to override and impossible to override with classes
  • 31. Antipatterns, Pt. II Long / unnecessarily specific selectors Example: body .container .sidebar .links Reasons: Adds weight and causes slower processing / paint times as it has to traverse the DOM to check for an exact match Adds confusion in terms of readability / maintainability Violates DRY Qualified Selectors
  • 32. FIN
  • 33. Resources Smashing Magazine -- CSS Specificity: Things You Should Know Mozilla’s Specificity Docs Smashing Magazine -- CSS Specificity & Inheritance How browsers work: Behind the scenes of modern web browsers Specificity calculator CSS Wizardry

Editor's Notes

  1. Intro: Senior UI dev at Cardinal Solutions, BG in product development Note: This presentation will be more about specificity than inheritance, but it will touch on topics of inheritance in regards to specificity, so it’s still relevant Also we’ll discuss CSS best practices which will help with inheritance as well
  2. Whether or not you use selectors in CSS has no bearing on whether the child will inherit. It has everything to do with overriding the inheritance by being aware of what kind of selector you need to write Note: According the Mozilla’s docs: “Styles for a directly targeted element will always take precedence over inherited styles, regardless of the specificity of the inherited rule.”
  3. CSS is simple to grasp, but if you want to work on a project that’s many pages or involves multiple people, then you need to understand how inheritance and specificity work Understanding specificity will help you minimize bugs and understand why styles aren’t applying -- we’ve all been there
  4. Why does this matter? Because knowing how browsers parse and interpret code allows you to make and justify better decisions and write faster, more efficient code
  5. UI backend -- for form controls, spacing in regards to the box model, etc Rendering Engine -- Chrome runs multiple instances of it for each tab, adding weight to processing
  6. Render tree -- contains basic styling info like color and the order of content. The layout is applied with the Layout Tree Paint -- this is where you see a lot of hang up too, especially if a lot of JS is involved in changing CSS styles. This is referred to as jank
  7. Not only does the browser have to download each linked file, opening an XHR request for each one, but it also has to run through the document and make references of the class attributes on HTML elements. It then has to compare those to the CSS declarations to find matches and partial matches. This is why more specific selectors (i.e., descendents) take longer, because instead of having to match only one class, it has to find a match for the entire selector 2) I.e., In the Bison parser, the selector “header nav ul li” a will find the first li item in the DOM tree, traverse up the tree to match every tag to the selector, then traverse all rulesets to find all matching rules. You can see how this gets expensive.
  8. 2) Is related to #1 in that h2.headline has more weight (a weight of 11) vs. .headline (a weight of 10) Note: Specificity doesn’t overwrite entire rulesets with the ruleset that has a higher specificity. It goes on a property by property basis. So if you have a general aside ruleset that gives it a padding of 10px and background-color of light grey, and then decide the .primary-navbar will have a background-color of blue, then the resulting styles applied will be a padding of 10px and a background-color of blue
  9. Note: If you use ID as an attribute, it will have the weight of an attribute (so, 10). This would look like: aside[id=“sidebar”] Pseudo-classes are things such as: :hover, :active, :disabled (typically describing a state). Note that :first-child, :nth-child are special cases of pseudo-classes called structural pseudo-classes, so it can be tricky. Pseudo-elements are elements that aren’t in the markup but are effectively inserted in the DOM, like ::after, ::before, and ::first-letter Note on !important: In the case that 2 conflicting rulesets both use !important, the browser will choose the ruleset which has a higher specificity weight. Also note on !important: This is the only way to override inline styles. So if you can’t touch the HTML and need to override legacy code, here’s your guy There are use cases where you are able to use !important, but those tend to be when it’s a change that won’t affect the entire website In some CSS naming conventions, it is recommended to use !important for state/utility styling (i.e., is-hidden) Also note that !important is utilized in IE8+
  10. 1 (1 tag element) 2 (2 tag elements) 13 (3 tag elements and 1 class) 23 (3 tag elements, 1 class, 1 pseudo-class ) 13 (3 tag elements, 1 class, negation is 0 ) 13 (3 tags, 1 attribute) 11 (1 tag and 1 attribute)
  11. Answer: It’ll be sky blue because all the selectors have the same weight, except for the tag selector, and the navigation--link is the last one
  12. Answer: It will be brown because the selectors are equal weight; it chooses the last one. It’s important to note that combinators such as > and ~ have no weight on specificity. They’re a part of inheritance instead, ensuring we only grab the a tags directly under our li tags, but we don’t apply the declarations to a tags which are in divs in li elms Note: The universal selector (*) and the negation pseudo-class :not also bear no weight under specificity rules. Also note it can be seen as bad practice for inheritance to use the universal selector, as that can break the rules of inheritance and it’s also a ding in performance
  13. Answer: It might surprise you, but the answer is that the background will be light green! This is because attribute selectors have a specificity weight of 10, thus making it 1 + 100 + 1 + 10 = 112!
  14. Answer: It’s going to be red, right? Wrong! Specificity is not inherited in this case! Since we’re using the parent element as a selector, it will apply to the parent element, but selecting “p” is more specific to the “p” tag than the parent’s selector. Thus the paragraph will be grey!
  15. Answer: 11 beats 10, right? Well...if this were simply math, but classes will always beat out elements. That’s the tricky thing about specificity. Each step up will always beat out the step beneath it.
  16. Answer: Inline styles are closer to the DOM, so those should apply right? Well in this case, remember that !important breaks all specificity rules. It is the only way to override inline styles. So it will be purple.
  17. Another exception is when you really DO want to select every item of that type instead of applying a class to each one. I.e., .main-navigation > li 4) This why BEM is so widely adopted, to help stick to low specificity and allow for use of DRY and minimal resets Using CSS also ensures that you have an even playing ground with specificity, so you’re not so worried about how it’ll behave. Note: You really want your code to document itself -- and writing good, semantic CSS is a part of this
  18. Only use !important to override third party stylesheets if you absolutely have to. And even then, it should only be used for page-specific CSS. Don’t use it on site wide CSS or standalone plugins that can be packaged separately 2) On IDs -- they can also be used for JS, but their main purpose is for landmarks and identification of elements; they’re so high in specificity because there’s only one per page 3) Note: The Descendents / Child selectors ARE better than straight up long selectors
  19. Sometimes it’s necessary to use longer selectors or descendents in your selectors; however, if writing from scratch they should be used sparingly and ONLY when you really mean it. If you need one, always go with child selectors. Note: While SASS is good in many ways, it makes it far too easy for inexperienced devs to follow these antipatterns. You tend to get trigger happy with nesting, but you need to be aware of the generated rulesets and how specific your selectors are. For that reason, I recommend learning the ins and outs of specificity before using SASS heavily