SlideShare uma empresa Scribd logo
1 de 80
CSS Architecture
Writing maintainable CSS
Alexei Skachykhin – Software Engineer
iTechArt, 2015
“Writing CSS is easy. Scaling CSS
and keeping it maintainable is not.”
Ben Frain
Guess what makes
it hard to maintain
“I don’t understand the cultural fascination with
failure being the source of great lessons to be
learned. You might know what won’t work, but you
still don’t know what will work.”
Basecamp
Excerpt from “Rework”
What’s missing?
CSS that works to spec isn’t enough, it
should be considered as a baseline
We need a plan to keep CSS styles organized.
We call such plan an architecture
Evolving Design
Growing Complexity
7,046
Rules
10K
Selectors
16,8K
Declarations
90
Unique Colors
Growing Complexity
3,938
Rules
5,164
Selectors
9,826
Declarations
46
Unique Colors
Repetitive Design
Repetitive Design
“We’re not designing pages,
we’re designing systems of components.”
Stephen Hay
Technical Difficulties
 Source order affects application order
 Specificity is hard to deal with
 CSS operate in global scope
 Permissive by its nature
1. Evolving Design
2. Growing Complexity
3. Repetitive Design
4. Technical Difficulties
It is time to follow architecture
and cleanup our CSS
Building Blocks
UI consists of components, where
component is any distinguishable element
of the design
Building Blocks
Writing CSS is not about making HTML
elements look like provided PSD, but
translating system of components into Web
compatible format
.contact-item {
float: left;
font-size: 28px;
.contact-item .contact-item__info {
margin-top: 4px;
margin-left: 20px;
padding-left: 31px;
}
.contact-item .contact-item__title {
margin: 0;
font-family: 'Lato', sans-serif;
font-size: 16px;
font-weight: bold;
}
.contact-item .contact-item__text {
margin: 1px 0 14px;
font-size: 14px;
}
}
.subscribe {
.clearfix();
.field-group {
.clearfix();
}
.sign-up-button {
.secondary-button;
.variant-action;
display: block;
border: none;
}
ul {
margin: 5px;
li {
display: inline-block;
}
}
}
COMPONENT STYLED HTML
Design and markup are inseparable.
Designers and Front-End Engineers must speak
ubiquitous language to succeed.
CSS Architecture
Components &
Other Styles
Dependency
Management
Physical Structure &
Deployment
No constraints?
Goals of Architecture
Predictable Reusable
Maintainable Scalable
Goals of Architecture
Predictable Reusable
Maintainable Scalable
Minimal
Complexity
“Everyone else in the W3C CSS Working Group, the
group which defines the future of CSS, fits the profile
of a developer much more than that of a designer.”
Lea Verou
Who’s in camp?
Existing Solutions
 BEM
 OOCSS
 SMACSS
 Atomic CSS
 MCSS
 ITCSS
Components
#1 DOM Independency
CSS component styles must not rely on
particular DOM structure
HERE
Example
div.social-links {
> div a {
color: blue;
}
}
 Visual styles are tightly coupled with
markup which makes them hard to
evolve
 Reusability of component is limited
 Ambiguity that leads to growth of
specificity
Rule
Avoid any signs of DOM elements in CSS
code including references to HTML tags, ID
(#) and (>) child selectors
Rule
CSS selectors must convey semantics of the
component and it’s integral parts. Class
selector conveys a lot, element selector
almost none
Example
.social-links {
.social-links__item {
color: blue;
}
}
#2 Location Independency
CSS component styles must not rely on
component’s location on a page
HERE
HERE
Example
.button {
color: white;
}
.sidebar {
.button {
color: orange;
}
}
 Component is no longer self contained
entity and its visual appearance is not
predictable at dev time
 Leads to growth of specificity
Rule
Component styles must not be written in
reliance on their location on a page, instead
provide location independent variations that
can be used anywhere
“Instead of saying - The buttons need to be smaller
when they’re in the header, we need to be saying - We
have a smaller variant of our buttons, and it’s these that
we use in the header.”
Harry Roberts
.button {
color: white;
/* Other declarations */
&.button--variant-action {
color: orange;
}
}
Example
#3 Limited Complexity
CSS components can be complex and have
integral parts, but no more than having 1 (2)
layers of descendant styles
HERE
Example
.filter {
.filter__header {
.filter__header__icon {
/* Declarations */
}
}
.filter__list {
.filter__list__link {
/* Declarations */
}
}
}
 Component is too complex which
makes it hard to maintain
 Following that style may lead to
unnecessary dependencies between
integral parts
Rule
If CSS styles have no dependency they must
not form parent-child relationship
Rule
Complex components must be split into
simpler components
.filter {
.filter__header {}
.filter__icon {
/* Declarations */
}
.filter__list {}
.filter__link {
/* Declarations */
}
}
Example
#4 Enforced Naming
All aspects of component definition must be named in a
way to communicate their relationship clearly and
protect from incorrect use
.infobox /* Block */ {
.infobox__body /* Element */ {}
.infobox__footer {}
.infobox__title {}
&.infobox--size-full /* Modifier */ {}
}
Example
#5 Explicit States
Dynamic behavior must be implemented with state
classes that JavaScript toggles. No direct style
manipulation is allowed with JavaScript.
HERE
open: function () {
elements.root.show();
elements.trigger.css('color', 'blue');
},
close: function () {
elements.root.hide();
elements.trigger.css('color', 'white');
}
Example
 Visual appearance of component is
now split across JavaScript and CSS
which makes is hard to maintain
 There is no simple undo operation
for setting style properties in
JavaScript so previous state has to
be maintained somewhere or inline
styles manipulated directly
open: function () {
elements.root.addClass('state-open');
elements.trigger.addClass('state-active');
},
close: function () {
elements.root.removeClass('state-open');
elements.trigger.removeClass('state-active');
}
Example
Rule
Global states must not collide with local
states to avoid overrides in CSS
.state-hidden {
display: none;
}
.infobox {
display: inline-block;
&.state-hidden {
display: inline-block;
visibility: hidden;
}
}
Example
 Component is no longer self contained
which causes inclusion of override
declarations
 In some cases may lead to a need to
have !importants
.global-state-hidden {
display: none;
}
.infobox {
display: inline-block;
&.state-hidden {
visibility: hidden;
}
}
Example
#6 JavaScript Hooks
Never use component classes to select elements with
JavaScript. Introduce specialized classes just for the
sake of selecting elements.
HERE
Example
var elements = {
mailing_list: internal.$e,
form: internal.$e.find('.social-widget__query'),
submit_button: internal.$e.find('.button'),
submit_button_text: internal.$e.find('span'),
validation_message: internal.$e.find('.social-widget__validation-message')
};
 Hard to modify component styles due to dependencies in
JavaScript. Makes whole component fragile
Example
<div class="social-widget social-widget--inversed js-mailing-list">
<div class="social-widget__title">Stay in the loop</div>
<form class="social-widget__query js-mailing-list-form">
<input class="js-mailing-list-email" type="text" name="email" placeholder="Email address">
<label class="button">
<span class="js-mailing-list-submit-button-text">Submit</span>
<input class="js-mailing-list-submit-button" type="submit">
</label>
</form>
<div class="js-mailing-list-validation-message social-widget__validation-message state-hidden">
Email is not in correct format!
</div>
</div>
#7 Local Media Queries
Responsiveness of a page must be based on
responsiveness of each component thus Media Query
must be local to a component
.blog-entry {
.blog-entry-body {
/* Declarations */
}
}
.infobox {}
@media @phone {
.blog-entry {
.blog-entry-body {
/* Declarations */
}
}
.infobox {}
}
Example
 Code duplication makes components
hard to maintain
 Components are not self-contained
which makes the outcome less
predictable at dev time
.blog-entry {
.blog-entry-body {
margin-right: @gutter / 2;
margin-bottom: @gutter / 2;
margin-left: @gutter / 2;
@media @phone {
margin-left: @gutter_phone / 2;
margin-right: @gutter_phone / 2;
}
}
}
Example
.infobox /* Component */ {
.infobox__body /* Integral Part */ {}
&.infobox--size-full /* Variant */ {}
&.state-active /* State */ {}
@media @phone /* Responsive */ {}
}
.js-infobox /* JavaScript Hook */
Anatomy of Component
#8 Layout vs Visual
Layout aspects should be moved to dedicated
components or integral parts
HERE
.infobox {
/* Layout */
float: left;
padding-left: @half-col-gutter;
padding-right: @half-col-gutter;
width: 33.33%;
/* Visual */
background-color: green;
padding: 10px; /* Collision */
}
Example
 Limits reusability
 Usually require additional html
elements just as styling hooks
Grid based layout is an emerging trend in Web and
Graphics design
.grid-row {
.clearfix();
.grid-row__column {
float: left;
padding-left: @half-col-gutter;
padding-right: @half-col-gutter;
width: 33.33%;
}
}
.infobox {
background-color: green;
padding: 10px;
}
Example
#9 Container vs Content
Container components must define layout and size
constraints, content components – visual look
(occasionally size constraints too)
Rule
Don’t make any assumptions about content
on container level
Rule
Develop CSS components to be container
agnostic
Other Styles
Types of Styles
Base
(Normalize, Reset)
Utilities
(clearfix, valign)
Typography
(Fonts, Headings, …)
Constants
(Colors, Sizes, …)
Physical Structure &
Deployment
Physical Structure
Single file for
all of the styles
Single file with
comments
One file per
type of styles
One file per
component
Fallacies
 Use id selectors for performance reasons
 Too many classes is a bad thing, style based on tags
 Nest CSS selectors to follow DOM hierarchy
 Put all styles into single file all the time because it is
easier to maintain
 Introduce lots of utility classes to have greater flexibility
when styling things
Thank you!
Forward your questions to
alexei.skachykhin@live.com

Mais conteúdo relacionado

Mais procurados

Cascading style sheets (CSS)
Cascading style sheets (CSS)Cascading style sheets (CSS)
Cascading style sheets (CSS)Harshita Yadav
 
Introduction to Cascading Style Sheets (CSS)
Introduction to Cascading Style Sheets (CSS)Introduction to Cascading Style Sheets (CSS)
Introduction to Cascading Style Sheets (CSS)Chris Poteet
 
Unit ii java script and xhtml documents and dynamic documents with javascript
Unit ii java script and xhtml documents and dynamic documents with javascriptUnit ii java script and xhtml documents and dynamic documents with javascript
Unit ii java script and xhtml documents and dynamic documents with javascriptzahid7578
 
Introduction to HTML and CSS
Introduction to HTML and CSSIntroduction to HTML and CSS
Introduction to HTML and CSSMario Hernandez
 
Cascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) helpCascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) helpcasestudyhelp
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - ObjectsWebStackAcademy
 
Intro to HTML & Semantic Markup (Chapter 2 - Sorta Brief Version)
Intro to HTML & Semantic Markup (Chapter 2 - Sorta Brief Version)Intro to HTML & Semantic Markup (Chapter 2 - Sorta Brief Version)
Intro to HTML & Semantic Markup (Chapter 2 - Sorta Brief Version)Nicole Ryan
 
Beginners css tutorial for web designers
Beginners css tutorial for web designersBeginners css tutorial for web designers
Beginners css tutorial for web designersSingsys Pte Ltd
 
CSS INHERITANCE
CSS INHERITANCECSS INHERITANCE
CSS INHERITANCEAnuradha
 
Intro to HTML & CSS
Intro to HTML & CSSIntro to HTML & CSS
Intro to HTML & CSSSyed Sami
 

Mais procurados (20)

HTML5
HTML5HTML5
HTML5
 
Cascading style sheets (CSS)
Cascading style sheets (CSS)Cascading style sheets (CSS)
Cascading style sheets (CSS)
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Introduction to Cascading Style Sheets (CSS)
Introduction to Cascading Style Sheets (CSS)Introduction to Cascading Style Sheets (CSS)
Introduction to Cascading Style Sheets (CSS)
 
Unit ii java script and xhtml documents and dynamic documents with javascript
Unit ii java script and xhtml documents and dynamic documents with javascriptUnit ii java script and xhtml documents and dynamic documents with javascript
Unit ii java script and xhtml documents and dynamic documents with javascript
 
HTML Introduction
HTML IntroductionHTML Introduction
HTML Introduction
 
Introduction to HTML and CSS
Introduction to HTML and CSSIntroduction to HTML and CSS
Introduction to HTML and CSS
 
Basic Details of HTML and CSS.pdf
Basic Details of HTML and CSS.pdfBasic Details of HTML and CSS.pdf
Basic Details of HTML and CSS.pdf
 
CSS
CSSCSS
CSS
 
Cascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) helpCascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) help
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Css
CssCss
Css
 
Intro to HTML & Semantic Markup (Chapter 2 - Sorta Brief Version)
Intro to HTML & Semantic Markup (Chapter 2 - Sorta Brief Version)Intro to HTML & Semantic Markup (Chapter 2 - Sorta Brief Version)
Intro to HTML & Semantic Markup (Chapter 2 - Sorta Brief Version)
 
Beginners css tutorial for web designers
Beginners css tutorial for web designersBeginners css tutorial for web designers
Beginners css tutorial for web designers
 
CSS Basics
CSS BasicsCSS Basics
CSS Basics
 
Html basics
Html basicsHtml basics
Html basics
 
What is css
What is cssWhat is css
What is css
 
CSS
CSSCSS
CSS
 
CSS INHERITANCE
CSS INHERITANCECSS INHERITANCE
CSS INHERITANCE
 
Intro to HTML & CSS
Intro to HTML & CSSIntro to HTML & CSS
Intro to HTML & CSS
 

Destaque

Maintainable CSS
Maintainable CSSMaintainable CSS
Maintainable CSSStephen Hay
 
The Duty to Report Up the Chain
The Duty to Report Up the ChainThe Duty to Report Up the Chain
The Duty to Report Up the ChainWendy Couture
 
Building Programming Abstractions for Wireless Sensor Networks Using Watershe...
Building Programming Abstractions for Wireless Sensor Networks Using Watershe...Building Programming Abstractions for Wireless Sensor Networks Using Watershe...
Building Programming Abstractions for Wireless Sensor Networks Using Watershe...M H
 
Focus group summary of finished product
Focus group summary of finished productFocus group summary of finished product
Focus group summary of finished productSaraMcgranaghan
 
5M Seth Civilization
5M Seth Civilization5M Seth Civilization
5M Seth CivilizationgsbSS
 
Course 2 week 6 lesson 10
Course 2 week 6 lesson 10Course 2 week 6 lesson 10
Course 2 week 6 lesson 10Joe Mellin
 
дорогой дружбы и добра
дорогой дружбы и добрадорогой дружбы и добра
дорогой дружбы и добраkillaruns
 
Survey
SurveySurvey
Surveysanaxo
 
Eliv 2015 bosch-hammel-presentation_v3.4
Eliv 2015 bosch-hammel-presentation_v3.4Eliv 2015 bosch-hammel-presentation_v3.4
Eliv 2015 bosch-hammel-presentation_v3.4Christof Hammel
 
Explore europewww.Tripmart.com
  Explore europewww.Tripmart.com  Explore europewww.Tripmart.com
Explore europewww.Tripmart.comtripmart
 
Chronology of computing
Chronology of computingChronology of computing
Chronology of computingAini_denzle
 

Destaque (20)

Atomic design
Atomic designAtomic design
Atomic design
 
Maintainable CSS
Maintainable CSSMaintainable CSS
Maintainable CSS
 
Java bmi
Java bmiJava bmi
Java bmi
 
Ucsf 2 3
Ucsf 2 3Ucsf 2 3
Ucsf 2 3
 
The Duty to Report Up the Chain
The Duty to Report Up the ChainThe Duty to Report Up the Chain
The Duty to Report Up the Chain
 
Building Programming Abstractions for Wireless Sensor Networks Using Watershe...
Building Programming Abstractions for Wireless Sensor Networks Using Watershe...Building Programming Abstractions for Wireless Sensor Networks Using Watershe...
Building Programming Abstractions for Wireless Sensor Networks Using Watershe...
 
Focus group summary of finished product
Focus group summary of finished productFocus group summary of finished product
Focus group summary of finished product
 
Urrunaga
UrrunagaUrrunaga
Urrunaga
 
Generacion de las computadoras
Generacion de las computadorasGeneracion de las computadoras
Generacion de las computadoras
 
Ucsf 3 3 ppt
Ucsf 3 3 pptUcsf 3 3 ppt
Ucsf 3 3 ppt
 
5M Seth Civilization
5M Seth Civilization5M Seth Civilization
5M Seth Civilization
 
Course 2 week 6 lesson 10
Course 2 week 6 lesson 10Course 2 week 6 lesson 10
Course 2 week 6 lesson 10
 
Corporate Gift Watches
Corporate Gift WatchesCorporate Gift Watches
Corporate Gift Watches
 
дорогой дружбы и добра
дорогой дружбы и добрадорогой дружбы и добра
дорогой дружбы и добра
 
Leroy Almon Sr. Bird
Leroy Almon Sr. BirdLeroy Almon Sr. Bird
Leroy Almon Sr. Bird
 
Survey
SurveySurvey
Survey
 
Eliv 2015 bosch-hammel-presentation_v3.4
Eliv 2015 bosch-hammel-presentation_v3.4Eliv 2015 bosch-hammel-presentation_v3.4
Eliv 2015 bosch-hammel-presentation_v3.4
 
Explore europewww.Tripmart.com
  Explore europewww.Tripmart.com  Explore europewww.Tripmart.com
Explore europewww.Tripmart.com
 
Elosu
ElosuElosu
Elosu
 
Chronology of computing
Chronology of computingChronology of computing
Chronology of computing
 

Semelhante a Maintainable CSS Architecture

Front end workflow Presentation at Coffee@DBG by Praveen Vijayan
Front end workflow Presentation at Coffee@DBG by Praveen VijayanFront end workflow Presentation at Coffee@DBG by Praveen Vijayan
Front end workflow Presentation at Coffee@DBG by Praveen VijayanDeepu S Nath
 
React Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdfReact Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdfBOSC Tech Labs
 
Inline style best practices in reactjs
Inline style best practices in reactjsInline style best practices in reactjs
Inline style best practices in reactjsBOSC Tech Labs
 
CSS Methodology
CSS MethodologyCSS Methodology
CSS MethodologyZohar Arad
 
Lightning web components - Introduction, component Lifecycle, Events, decorat...
Lightning web components - Introduction, component Lifecycle, Events, decorat...Lightning web components - Introduction, component Lifecycle, Events, decorat...
Lightning web components - Introduction, component Lifecycle, Events, decorat...Nidhi Sharma
 
Rock Solid CSS Architecture
Rock Solid CSS ArchitectureRock Solid CSS Architecture
Rock Solid CSS ArchitectureJohn Need
 
Web components - An Introduction
Web components - An IntroductionWeb components - An Introduction
Web components - An Introductioncherukumilli2
 
Intro to MVC 3 for Government Developers
Intro to MVC 3 for Government DevelopersIntro to MVC 3 for Government Developers
Intro to MVC 3 for Government DevelopersFrank La Vigne
 
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan
 
CSS101 - Concept Fundamentals for non UI Developers
CSS101 - Concept Fundamentals for non UI DevelopersCSS101 - Concept Fundamentals for non UI Developers
CSS101 - Concept Fundamentals for non UI DevelopersDarren Gideon
 
Architecture Specification - Visual Modeling Tool
Architecture Specification - Visual Modeling ToolArchitecture Specification - Visual Modeling Tool
Architecture Specification - Visual Modeling ToolAdriaan Venter
 
Building and Deployment of Drupal sites with Features and Context
Building and Deployment of Drupal sites with Features and ContextBuilding and Deployment of Drupal sites with Features and Context
Building and Deployment of Drupal sites with Features and ContextSvilen Sabev
 
Blog It Up, Baby! Extending the new IBM Lotus Domino Blog Template
Blog It Up, Baby! Extending the new IBM Lotus Domino Blog TemplateBlog It Up, Baby! Extending the new IBM Lotus Domino Blog Template
Blog It Up, Baby! Extending the new IBM Lotus Domino Blog TemplateSean Burgess
 

Semelhante a Maintainable CSS Architecture (20)

Unit 2 - Data Binding.pptx
Unit 2 - Data Binding.pptxUnit 2 - Data Binding.pptx
Unit 2 - Data Binding.pptx
 
Fewd week2 slides
Fewd week2 slidesFewd week2 slides
Fewd week2 slides
 
Front end workflow Presentation at Coffee@DBG by Praveen Vijayan
Front end workflow Presentation at Coffee@DBG by Praveen VijayanFront end workflow Presentation at Coffee@DBG by Praveen Vijayan
Front end workflow Presentation at Coffee@DBG by Praveen Vijayan
 
React Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdfReact Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdf
 
CSC PPT 4.pptx
CSC PPT 4.pptxCSC PPT 4.pptx
CSC PPT 4.pptx
 
Inline style best practices in reactjs
Inline style best practices in reactjsInline style best practices in reactjs
Inline style best practices in reactjs
 
CSS Methodology
CSS MethodologyCSS Methodology
CSS Methodology
 
Lightning web components - Introduction, component Lifecycle, Events, decorat...
Lightning web components - Introduction, component Lifecycle, Events, decorat...Lightning web components - Introduction, component Lifecycle, Events, decorat...
Lightning web components - Introduction, component Lifecycle, Events, decorat...
 
Rock Solid CSS Architecture
Rock Solid CSS ArchitectureRock Solid CSS Architecture
Rock Solid CSS Architecture
 
Web components - An Introduction
Web components - An IntroductionWeb components - An Introduction
Web components - An Introduction
 
Intro to MVC 3 for Government Developers
Intro to MVC 3 for Government DevelopersIntro to MVC 3 for Government Developers
Intro to MVC 3 for Government Developers
 
Test
TestTest
Test
 
Custom PrimeFaces components
Custom PrimeFaces componentsCustom PrimeFaces components
Custom PrimeFaces components
 
Web technologies part-2
Web technologies part-2Web technologies part-2
Web technologies part-2
 
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2
 
CSS101 - Concept Fundamentals for non UI Developers
CSS101 - Concept Fundamentals for non UI DevelopersCSS101 - Concept Fundamentals for non UI Developers
CSS101 - Concept Fundamentals for non UI Developers
 
Architecture Specification - Visual Modeling Tool
Architecture Specification - Visual Modeling ToolArchitecture Specification - Visual Modeling Tool
Architecture Specification - Visual Modeling Tool
 
Building and Deployment of Drupal sites with Features and Context
Building and Deployment of Drupal sites with Features and ContextBuilding and Deployment of Drupal sites with Features and Context
Building and Deployment of Drupal sites with Features and Context
 
Blog It Up, Baby! Extending the new IBM Lotus Domino Blog Template
Blog It Up, Baby! Extending the new IBM Lotus Domino Blog TemplateBlog It Up, Baby! Extending the new IBM Lotus Domino Blog Template
Blog It Up, Baby! Extending the new IBM Lotus Domino Blog Template
 
Coding standards
Coding standards Coding standards
Coding standards
 

Mais de Alexei Skachykhin

Mais de Alexei Skachykhin (6)

Representational State Transfer
Representational State TransferRepresentational State Transfer
Representational State Transfer
 
Web Real-time Communications
Web Real-time CommunicationsWeb Real-time Communications
Web Real-time Communications
 
Code Contracts
Code ContractsCode Contracts
Code Contracts
 
JavaScript as Development Platform
JavaScript as Development PlatformJavaScript as Development Platform
JavaScript as Development Platform
 
HTML5 Comprehensive Guide
HTML5 Comprehensive GuideHTML5 Comprehensive Guide
HTML5 Comprehensive Guide
 
Windows 8
Windows 8Windows 8
Windows 8
 

Último

chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 

Último (20)

chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 

Maintainable CSS Architecture

  • 1. CSS Architecture Writing maintainable CSS Alexei Skachykhin – Software Engineer iTechArt, 2015
  • 2. “Writing CSS is easy. Scaling CSS and keeping it maintainable is not.” Ben Frain
  • 3.
  • 4. Guess what makes it hard to maintain
  • 5.
  • 6.
  • 7.
  • 8. “I don’t understand the cultural fascination with failure being the source of great lessons to be learned. You might know what won’t work, but you still don’t know what will work.” Basecamp Excerpt from “Rework”
  • 9. What’s missing? CSS that works to spec isn’t enough, it should be considered as a baseline
  • 10. We need a plan to keep CSS styles organized. We call such plan an architecture
  • 15. Repetitive Design “We’re not designing pages, we’re designing systems of components.” Stephen Hay
  • 16. Technical Difficulties  Source order affects application order  Specificity is hard to deal with  CSS operate in global scope  Permissive by its nature
  • 17. 1. Evolving Design 2. Growing Complexity 3. Repetitive Design 4. Technical Difficulties
  • 18. It is time to follow architecture and cleanup our CSS
  • 19. Building Blocks UI consists of components, where component is any distinguishable element of the design
  • 20.
  • 21. Building Blocks Writing CSS is not about making HTML elements look like provided PSD, but translating system of components into Web compatible format
  • 22. .contact-item { float: left; font-size: 28px; .contact-item .contact-item__info { margin-top: 4px; margin-left: 20px; padding-left: 31px; } .contact-item .contact-item__title { margin: 0; font-family: 'Lato', sans-serif; font-size: 16px; font-weight: bold; } .contact-item .contact-item__text { margin: 1px 0 14px; font-size: 14px; } } .subscribe { .clearfix(); .field-group { .clearfix(); } .sign-up-button { .secondary-button; .variant-action; display: block; border: none; } ul { margin: 5px; li { display: inline-block; } } } COMPONENT STYLED HTML
  • 23. Design and markup are inseparable. Designers and Front-End Engineers must speak ubiquitous language to succeed.
  • 24. CSS Architecture Components & Other Styles Dependency Management Physical Structure & Deployment
  • 26. Goals of Architecture Predictable Reusable Maintainable Scalable
  • 27. Goals of Architecture Predictable Reusable Maintainable Scalable Minimal Complexity
  • 28. “Everyone else in the W3C CSS Working Group, the group which defines the future of CSS, fits the profile of a developer much more than that of a designer.” Lea Verou
  • 30. Existing Solutions  BEM  OOCSS  SMACSS  Atomic CSS  MCSS  ITCSS
  • 32. #1 DOM Independency CSS component styles must not rely on particular DOM structure
  • 33. HERE
  • 34. Example div.social-links { > div a { color: blue; } }  Visual styles are tightly coupled with markup which makes them hard to evolve  Reusability of component is limited  Ambiguity that leads to growth of specificity
  • 35. Rule Avoid any signs of DOM elements in CSS code including references to HTML tags, ID (#) and (>) child selectors
  • 36. Rule CSS selectors must convey semantics of the component and it’s integral parts. Class selector conveys a lot, element selector almost none
  • 38. #2 Location Independency CSS component styles must not rely on component’s location on a page
  • 40. Example .button { color: white; } .sidebar { .button { color: orange; } }  Component is no longer self contained entity and its visual appearance is not predictable at dev time  Leads to growth of specificity
  • 41. Rule Component styles must not be written in reliance on their location on a page, instead provide location independent variations that can be used anywhere
  • 42. “Instead of saying - The buttons need to be smaller when they’re in the header, we need to be saying - We have a smaller variant of our buttons, and it’s these that we use in the header.” Harry Roberts
  • 43. .button { color: white; /* Other declarations */ &.button--variant-action { color: orange; } } Example
  • 44. #3 Limited Complexity CSS components can be complex and have integral parts, but no more than having 1 (2) layers of descendant styles
  • 45. HERE
  • 46. Example .filter { .filter__header { .filter__header__icon { /* Declarations */ } } .filter__list { .filter__list__link { /* Declarations */ } } }  Component is too complex which makes it hard to maintain  Following that style may lead to unnecessary dependencies between integral parts
  • 47. Rule If CSS styles have no dependency they must not form parent-child relationship
  • 48. Rule Complex components must be split into simpler components
  • 49. .filter { .filter__header {} .filter__icon { /* Declarations */ } .filter__list {} .filter__link { /* Declarations */ } } Example
  • 50. #4 Enforced Naming All aspects of component definition must be named in a way to communicate their relationship clearly and protect from incorrect use
  • 51. .infobox /* Block */ { .infobox__body /* Element */ {} .infobox__footer {} .infobox__title {} &.infobox--size-full /* Modifier */ {} } Example
  • 52. #5 Explicit States Dynamic behavior must be implemented with state classes that JavaScript toggles. No direct style manipulation is allowed with JavaScript.
  • 53. HERE
  • 54. open: function () { elements.root.show(); elements.trigger.css('color', 'blue'); }, close: function () { elements.root.hide(); elements.trigger.css('color', 'white'); } Example  Visual appearance of component is now split across JavaScript and CSS which makes is hard to maintain  There is no simple undo operation for setting style properties in JavaScript so previous state has to be maintained somewhere or inline styles manipulated directly
  • 55. open: function () { elements.root.addClass('state-open'); elements.trigger.addClass('state-active'); }, close: function () { elements.root.removeClass('state-open'); elements.trigger.removeClass('state-active'); } Example
  • 56. Rule Global states must not collide with local states to avoid overrides in CSS
  • 57. .state-hidden { display: none; } .infobox { display: inline-block; &.state-hidden { display: inline-block; visibility: hidden; } } Example  Component is no longer self contained which causes inclusion of override declarations  In some cases may lead to a need to have !importants
  • 58. .global-state-hidden { display: none; } .infobox { display: inline-block; &.state-hidden { visibility: hidden; } } Example
  • 59. #6 JavaScript Hooks Never use component classes to select elements with JavaScript. Introduce specialized classes just for the sake of selecting elements.
  • 60. HERE
  • 61. Example var elements = { mailing_list: internal.$e, form: internal.$e.find('.social-widget__query'), submit_button: internal.$e.find('.button'), submit_button_text: internal.$e.find('span'), validation_message: internal.$e.find('.social-widget__validation-message') };  Hard to modify component styles due to dependencies in JavaScript. Makes whole component fragile
  • 62. Example <div class="social-widget social-widget--inversed js-mailing-list"> <div class="social-widget__title">Stay in the loop</div> <form class="social-widget__query js-mailing-list-form"> <input class="js-mailing-list-email" type="text" name="email" placeholder="Email address"> <label class="button"> <span class="js-mailing-list-submit-button-text">Submit</span> <input class="js-mailing-list-submit-button" type="submit"> </label> </form> <div class="js-mailing-list-validation-message social-widget__validation-message state-hidden"> Email is not in correct format! </div> </div>
  • 63. #7 Local Media Queries Responsiveness of a page must be based on responsiveness of each component thus Media Query must be local to a component
  • 64. .blog-entry { .blog-entry-body { /* Declarations */ } } .infobox {} @media @phone { .blog-entry { .blog-entry-body { /* Declarations */ } } .infobox {} } Example  Code duplication makes components hard to maintain  Components are not self-contained which makes the outcome less predictable at dev time
  • 65. .blog-entry { .blog-entry-body { margin-right: @gutter / 2; margin-bottom: @gutter / 2; margin-left: @gutter / 2; @media @phone { margin-left: @gutter_phone / 2; margin-right: @gutter_phone / 2; } } } Example
  • 66. .infobox /* Component */ { .infobox__body /* Integral Part */ {} &.infobox--size-full /* Variant */ {} &.state-active /* State */ {} @media @phone /* Responsive */ {} } .js-infobox /* JavaScript Hook */ Anatomy of Component
  • 67. #8 Layout vs Visual Layout aspects should be moved to dedicated components or integral parts
  • 68. HERE
  • 69. .infobox { /* Layout */ float: left; padding-left: @half-col-gutter; padding-right: @half-col-gutter; width: 33.33%; /* Visual */ background-color: green; padding: 10px; /* Collision */ } Example  Limits reusability  Usually require additional html elements just as styling hooks
  • 70. Grid based layout is an emerging trend in Web and Graphics design
  • 71. .grid-row { .clearfix(); .grid-row__column { float: left; padding-left: @half-col-gutter; padding-right: @half-col-gutter; width: 33.33%; } } .infobox { background-color: green; padding: 10px; } Example
  • 72. #9 Container vs Content Container components must define layout and size constraints, content components – visual look (occasionally size constraints too)
  • 73. Rule Don’t make any assumptions about content on container level
  • 74. Rule Develop CSS components to be container agnostic
  • 76. Types of Styles Base (Normalize, Reset) Utilities (clearfix, valign) Typography (Fonts, Headings, …) Constants (Colors, Sizes, …)
  • 78. Physical Structure Single file for all of the styles Single file with comments One file per type of styles One file per component
  • 79. Fallacies  Use id selectors for performance reasons  Too many classes is a bad thing, style based on tags  Nest CSS selectors to follow DOM hierarchy  Put all styles into single file all the time because it is easier to maintain  Introduce lots of utility classes to have greater flexibility when styling things
  • 80. Thank you! Forward your questions to alexei.skachykhin@live.com

Notas do Editor

  1. Всё начинается хорошо, но потом становится сложно сопровождать.
  2. Второй раз ты пытаешься хорошо писать свойства CSS, но всё равно что-то идёт не так.
  3. Interestingly, we don’t usually make this oversight with other languages. A Rails developer isn’t considered good just because his code works to spec. This is considered baseline. Of course it must work to spec; its merit is based on other things: Is the code readable? Is it easy to change or extend? Is it decoupled from other parts of the application? Will it scale?
  4. Тут важно сказать что подсознательно первое о чём мы думаем – это то что мы можем работать без плана. Но как было показано на примере это не работает! И дальше пойдёт описание driving forces.
  5. Interestingly, we don’t usually make this oversight with other languages. A Rails developer isn’t considered good just because his code works to spec. This is considered baseline. Of course it must work to spec; its merit is based on other things: Is the code readable? Is it easy to change or extend? Is it decoupled from other parts of the application? Will it scale?
  6. Требования к CSS архитектуре такие же как и к архитектуре программных компонентов -> Переход на следующий слайд
  7. Требования к CSS архитектуре такие же как и к архитектуре программных компонентов -> Переход на следующий слайд