65
CSS Best Practices, Style Guide, and Tips #ITDEVCON Chris Love http://love2dev.com @ChrisLove

Css best practices style guide and tips

Embed Size (px)

Citation preview

Page 1: Css best practices style guide and tips

CSS Best Practices, Style Guide, and Tips

#ITDEVCON

Chris Lovehttp://love2dev.com@ChrisLove

Page 2: Css best practices style guide and tips

Who Am I?• ASP.NET MVP• ASP Insider•MS Edge User Agent• Author• Speaker• Tweaker, Lover of Web, JavaScript, CSS & HTML5•@ChrisLove• Love2Dev.com

#ITDEVCON

Page 3: Css best practices style guide and tips

High Performance Single Page Web Applications• Responsive Design• Touch• Mobile First• SPA• Extensible, Scalable Architecture• Web Build and Workflow• Goes Really Fast!

• ~395 Pages• 20 Chapters• $9.99

#ITDEVCON

Page 4: Css best practices style guide and tips

Slide Decks & Source Code• Slide Deck – http://slidesha.re/19NZInK• Source Code – http://GitHub.com/docluv

#ITDEVCON

Page 5: Css best practices style guide and tips

CSS• Language Defining Rendering Rules

#ITDEVCON

Page 6: Css best practices style guide and tips

CSS.main-content { overflow: hidden; left: 6.3166666%; right: 0; top: 50px; bottom: 4.166666%; position: absolute; border-radius: 5px 5px 0 0; background-color: #000000; -moz-transition: all 700ms ease-out; -o-transition: all 700ms ease-out; -webkit-transition: all 700ms ease-out; transition: all 700ms ease-out;}

#ITDEVCON

Selector/Rule

Properties

Vendor Specific

Page 7: Css best practices style guide and tips

CSS•Rules•Defined using selector syntax

•Properties• The specifics

•Media Queries•Define Rules Based on Browser & Device Characteristics

#ITDEVCON

Page 8: Css best practices style guide and tips

CSS Property Units•px – pixels•% - percent•em – relative to the element’s font-size• rem – Relative to the root element’s font-size•vh/vw – Viewport Height/Viewport Width•Any 0 does not require a unit

#ITDEVCON

Page 9: Css best practices style guide and tips

CSS Selector Syntax• Element• H1, DIV, P

• Class• .btn, . spa-child-view

• ID• #tryToAvoid

#ITDEVCON

Page 10: Css best practices style guide and tips

Advanced CSS Selector Syntax• Nested Selectors

• Allows You To Apply Rules to Children of Matched Elements• .main-content p• Be careful to avoid complexity

• Dynamic By Attributes• script[class='spa-view']

#ITDEVCON

Page 11: Css best practices style guide and tips

By Attribute/typeinput[type="email"] {

color:blue; }

#ITDEVCON

Page 12: Css best practices style guide and tips

Starts With[class^="my-class-"] {

color:red; }

#ITDEVCON

Page 13: Css best practices style guide and tips

Ends With[class$=“-my-class"] {

color:red; }

#ITDEVCON

Page 14: Css best practices style guide and tips

Contains[class*="class"] {

color:red; }

#ITDEVCON

Page 15: Css best practices style guide and tips

Customize Social Linksa[href*="twitter.com"] { color:#55acee; } a[href*="facebook.com"] { color:#3b5998; } a[href*="google.com"] { color:#db4437; }

#ITDEVCON

Page 16: Css best practices style guide and tips

Remove webkit Input Borderinput[type="text"]:focus { outline: none; }

#ITDEVCON

Page 17: Css best practices style guide and tips

psuedo-classes•Define CSS Rules for Element States• Hover• Active

•Define Rules for hidden elements• :before, :after

•Define Rules for nth Element• :nth-of-type(3n)

Page 18: Css best practices style guide and tips

Content Property•Defines ‘text’ value for matched element•Useful with :before and :after pseudo element

Page 19: Css best practices style guide and tips

Responsive Table Trick• Tables Create a Unique Responsive Design Problem• Change CSS To Change Rendering Rules• Turn Table into a fake set of DIVs• Leverage content property to define value labels

• https://css-tricks.com/responsive-data-tables/

Page 20: Css best practices style guide and tips

#ITDEVCON

Page 21: Css best practices style guide and tips

Responsive Table Trick<table>

<thead>

<tr>

<th>First Name</th>

<th>Last Name</th>

<th>Job Title</th>

</tr>

</thead>

<tbody>

<tr>

<td>James</td>

<td>Matman</td>

<td>Chief Sandwich Eater</td>

</tr>

<tr>

<td>The</td>

<td>Tick</td>

<td>Crimefighter Sorta</td>

</tr>

</tbody>

</table>

Page 22: Css best practices style guide and tips

Responsive Table Trick@media only screen and (max-width: 760px),(min-device-width: 768px) and (max-device-width: 1024px) {

table, thead, tbody, th, td, tr { display: block;

}

}#ITDEVCON

Page 23: Css best practices style guide and tips

Responsive Table Tricktd:nth-of-type(1):before { content: "First Name"; }td:nth-of-type(2):before { content: "Last Name"; }td:nth-of-type(3):before { content: "Job Title"; }td:nth-of-type(4):before { content: "Favorite Color"; }td:nth-of-type(5):before { content: "Wars of Trek?"; }td:nth-of-type(6):before { content: "Porn Name"; }td:nth-of-type(7):before { content: "Date of Birth"; }td:nth-of-type(8):before { content: "Dream Vacation City"; }td:nth-of-type(9):before { content: "GPA"; }td:nth-of-type(10):before { content: "Arbitrary Data"; }

Page 24: Css best practices style guide and tips

CSS Selector Specificity• Complex Specificity

• .main-content > article #myArticleId p• Leads to large CSS files• Makes Code Unmanageable• Lower the Score the Better

• Browsers Parse Selectors Right to Left• * Avoid Universal Selector

Page 25: Css best practices style guide and tips

Right-Left Rule• .main-content > article #myArticleId p• Translates to:

• #myArticleId p• Think More Like the Browser When Defining Selectors

Page 26: Css best practices style guide and tips

Calculate CSS Specificity• Count the Inline Style• count the number of ID selectors in the selector (= a) • count the number of class selectors, attributes selectors,

and pseudo-classes in the selector (= b) • count the number of type selectors and pseudo-elements

in the selector (= c) • ignore the universal selector

Page 27: Css best practices style guide and tips

Calculate CSS Specificity

http://specificity.keegan.st/

Page 28: Css best practices style guide and tips

BEM Naming Convention• Block• Element•Modifier

• Bootstrap and Primer Good Examples

Page 29: Css best practices style guide and tips

BEM Naming Convention• .btn {…}• .btn-primary {…}• .btn-primary:disabled {…}• .btn-xs {…}

•Might also see __ between words

Page 30: Css best practices style guide and tips

BEM Naming Convention• <button type="button" class="btn btn-primary">Primary</button>• <button type="button" class="btn btn-success">Success</button>• <button type="button" class="btn btn-info">Info</button> • <button type="button" class="btn btn-warning">Warning</button>

Page 31: Css best practices style guide and tips

CSS Cascading• Last, Most Specific Rule Wins• Be mindful of your CSS Definition Order

•Overwrites Previously Defined Rules• Simple rule make this easy to maintain and create

Page 32: Css best practices style guide and tips

Responsive Design“this unspoken agreement to pretend that we had a certain size. And that size changed over the years. For a while, we all sort of tacitly agreed that 640 by 480 was the right size, and then later than changed to 800:600, and 1024; we seem to have settled on this 960 pixel as being this like, default. It’s still unknown. We still don’t know the size of the browser; it’s just like this consensual hallucination that we’ve all agreed to participate in: “Let’s assume the browser has a browser width of at least 960 pixels.”

Jeremy Keithbit.ly/1bhH6rw

Page 33: Css best practices style guide and tips

Responsive Web Design

#ITDEVCON

Page 34: Css best practices style guide and tips

Responsive Web Design• Introduced by Ethan Marcotte 2010 -

bit.ly/178an9e• Web Design Approach To Create An Optimal

Viewing Experience Across All Browser ViewPorts• Fluid Layouts• Media Queries• Minimal if any JavaScript Required

Page 35: Css best practices style guide and tips

Fluid Layout

• Stretch as the Browser ViewPort Changes• Browser’s Viewable Area Inside the Chrome

• Serve as the Foundation for the Web Application Layout• Great Way To Create Native Like Experience

Page 36: Css best practices style guide and tips

Fluid Layout

• Leverage Absolute Positioning• Enables Fixed Positioning Without

position:fixed• Leverage overflow scrolling

Page 37: Css best practices style guide and tips

Media Queries@media (min-width: 600px) { /* Selectors & Rules */}

@media (min-width: 820px) { /* Selectors & Rules */ }

@media (min-width: 1080px) { /* Selectors & Rules */}

Page 38: Css best practices style guide and tips

Avoid Embedded Styles•Don't separate content from design• Cause more maintenance headaches•Make your pages larger•Do not take advantage of Http Caching• Lead to Duplicate Rules

Page 39: Css best practices style guide and tips

CSS - Files• Should• Use External Files• Hosted on a CDN• Bundled & Minified *

• HTTP/2 Changes the Bundling Rule

Page 40: Css best practices style guide and tips

CSS – Debug Files• Should• Use Many Files• They Should Correlate to a Purpose

• View• Component• Layout

Page 41: Css best practices style guide and tips

CSS –Filescss/

site.min.css/dev

/libs/ui/views

Page 42: Css best practices style guide and tips

CSS Best Practices• Link to External Files in the HEAD• Ensures CSS read before HTML

• Avoid Using @import• Causes CSS to be Parsed After Document

Page 43: Css best practices style guide and tips

CSS Reset• Establishes a Common Base• Each Browser has a default CSS stylesheet•Many Resets Availble• Normalize.css probably most popular• Popular libraries have resets; ex bootstrap uses

normalize

Page 44: Css best practices style guide and tips

CSS Libraries•Many Available• Bootstrap is the current defacto standard• Primer based on Boostrap• Created by bootstrap author• GitHub’s internal library

• https://github.com/primer/primer

Page 45: Css best practices style guide and tips

CSS Libraries• Be Careful to not be Completely Dependent on Library•Understand How CSS Rules, Apply Best Practices• Build Your Own Custom Version

• Grunt/Gulp

Page 46: Css best practices style guide and tips

Critical CSS• The CSS Required to Render The Above the Fold Content• Embed Inline, in HEAD element• Instant Render if HTML < 14kb• Works great for a SPA

• criticalCSS Node Module• https://www.npmjs.com/package/criticalcss

Page 47: Css best practices style guide and tips

Critical CSS Gruntgrunt.initConfig({ criticalcss: { custom: { options: { url: "http://localhost:4000", width: 1200, height: 900, outputfile: "dist/critical.css", filename: "/path/to/local/all.css", // Using path.resolve( path.join( ... ) ) is a good idea here buffer: 800*1024, ignoreConsole: false } } },});

Page 48: Css best practices style guide and tips

UnCSS Grunt uncss: { dist: { src: ['app/index.html'], dest: 'app/css/tidy.css', options: { report: 'min' } } }

https://www.npmjs.com/package/grunt-uncss

Page 49: Css best practices style guide and tips

CSS Code Style•Define Section Titles

/*------------------------------------*\ $MAIN\*------------------------------------*/

Page 50: Css best practices style guide and tips

CSS Rule Formatting•Use one discrete selector per line in multi-selector rulesets.• Include a single space before the opening brace of a ruleset.• Include one declaration per line in a declaration block.•Use one level of indentation for each declaration.• Include a single space after the colon of a declaration.

Page 51: Css best practices style guide and tips

CSS Rule Formatting•Use lowercase and shorthand hex values, e.g., `#aaa`.•Use single or double quotes consistently. Preference is for double quotes, e.g., `content: ""`.•Quote attribute values in selectors, e.g., `input[type="checkbox"]`.• _Where allowed_, avoid specifying units for zero-values, e.g., `margin: 0`.

Page 52: Css best practices style guide and tips

CSS Rule Formatting• Include a space after each comma in comma-separated property or function values.• Include a semi-colon at the end of the last declaration in a declaration block.• Place the closing brace of a ruleset in the same column as the first character of the ruleset.• Separate each ruleset by a blank line.

Page 53: Css best practices style guide and tips

Rule Formatting Example.selector-1,.selector-2,.selector-3[type="text"] { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; display: block; font-family: helvetica, arial, sans-serif; color: #333; background: #fff; background: linear-gradient(#fff, rgba(0, 0, 0, 0.8));}

Page 54: Css best practices style guide and tips

Consistently Declare Property Order•Makes it Easier to Read•Makes it Easier for Teams to Share Code

Page 55: Css best practices style guide and tips

Consistently Declare Property Order

.selector { /* Positioning */ position: absolute; z-index: 10; top: 0; right: 0; bottom: 0; left: 0;

  /* Display & Box Model */ display: inline-block; overflow: hidden; box-sizing: border-box; width: 100px; height: 100px; padding: 10px; border: 10px solid #333; margin: 10px; 

/* Other */ background: #000; color: #fff; font-family: sans-serif; font-size: 16px; text-align: right;}

Page 56: Css best practices style guide and tips

Clock-Wise Rule•Margin & Padding Work Clock-wise around the element•margin: 5% 10% 15% 20%;•margin-top : 5%;•margin-right : 10%;•margin-bottom : 15%;•margin-left : 20%;

Page 57: Css best practices style guide and tips

Element Layout Box

Page 58: Css best practices style guide and tips

CSS Animations•Do Not Use JavaScript Libraries for Animations• CSS Animations are Native• Run on the GPU

Page 59: Css best practices style guide and tips

CSS Key-Frame Animations• Allow You To Define Complex Animations

• Define Rules/Properties Along a Timeline• Animate.css is a collection of turn-key animations

• http://daneden.me/animate

Page 60: Css best practices style guide and tips

CSS Key-Frame Animations• Can be Applied by adding and removing CSS classes on an element

loginDlg.classList.add("fadeInDown"); showLogin.classList.add("fadeOut"); loginDlg.classList.remove("fadeOutUp");

Page 61: Css best practices style guide and tips

CSS Key-Frame Animations• Can be Applied by adding and removing CSS classes on an element

loginDlg.classList.add("fadeInDown"); showLogin.classList.add("fadeOut"); loginDlg.classList.remove("fadeOutUp");

• http://bit.ly/1Lt1kTb

Page 62: Css best practices style guide and tips

CSS Shapes• CSS Can be Used to Create All Sorts of Shapes• http://www.cssshapes.com/

Page 63: Css best practices style guide and tips

Create a CSS Heart•My Site’s Logo is a CSS Heart•Here is how to create it:• http://bit.ly/1NF3Sjf

Page 64: Css best practices style guide and tips

Perfectly Align to Center.my-class-parent { position:relative; }

.my-class { position:absolute; top:50%; left:50%; -webkit-transform:translate(-50%, -50%); transform:translate(-50%, -50%); }

Page 65: Css best practices style guide and tips

High Performance Single Page Web Applications

• Responsive Design• Touch• Mobile First• SPA• Extensible, Scalable Architecture• Web Build and Workflow• Goes Really Fast!

• ~395 Pages• 20 Chapters• $9.99