The trouble with CSS... – The language – CSS Precomilers



The trouble with CSS... – The language – CSS Precomilers

0 0


css-presentation

presentation using reveal.js and htmlbuild grunt

On Github martin-riley / css-presentation

The state of CSS

By Martin Riley

Current development of Cascading Style Sheets and development methodologies.

They'll be hidden in your presentation, but you can see them if you open the speaker notes window (hit 's' on your keyboard).

Agenda

  • CSS language limitations
  • Issues with maintaining a large code base
  • How to get up and running
  • New CSS features
  • Layout modules

Looking at language limitations

Issues faced on Bookatable

Ways of getting started

New modules and methods

Layout modules

The trouble with CSS...

The language

  • No validation
  • No variables
  • No logic

DOWN...

Unlike C# or server lanugages, no validation unless you use online services

There's no contants or variables - use find change to replace

Static language, no way to manipulate the style on the fly

The trouble with CSS...

Cosmetic

  • Vertical centering
  • Equal height columns
  • Limited positioning tools

DOWN...

vertical centering hard when height of item is not known

min-height or hacks to achive equal height cols

mostly achieved through float - originally designed for images and text

The trouble with CSS...

Architectural

  • The cascade is global
  • Naming conflicts
  • Sub-tree matching

Right

Architectural problems, The cascade is global, and every rule you write has the potential to affect entirely unrelated parts of the site.

CSS will not warn you if you use a class selector that already exists in your stylesheet. Limiting the scope of a selector to a particular DOM subtree does guarantee that it won’t affect elements outside of that subtree.

The problem is it doesn’t guarantee that it won’t unintentionally affect elements within the same subtree.

CSS Precomilers

  • SASS (Syntactically Awesome Stylesheets Sass)
  • LESS (Stylesheet Language)
  • Both provide an extension language to compile down to CSS

Partials

SASS and LESS lets you use features that don't exist in CSS yet like variables, nesting, mixins, inheritance and operator functions.

Compiler is built upon Ruby.

Partials - split code into modules

Watches for file changes and compiles

Works with livereload

Variables

$font-stack: Helvetica, sans-serif;
$primary-color: #333;

body {
  font: 100% $font-stack;
  color: $primary-color;
}

/* CSS */
body { font: 100% Helvetica, sans-serif; color: #333; }

Operators

+ Addition - Subtraction * Multiplication / Division % Modulus

Control Directives & Expressions

@if (Boolean) @for (@for $var from <start> to <end>) @each (@each $author in $list) @while (@while $types > 0) Control directives are an advanced feature, and are uncommon in day-to-day styling. They exist mainly for use in mixins, particularly those that are part of libraries like Compass, and so require substantial flexibility.

Nesting

nav {
    background-color: yellow;
    
    ul {
        margin: 0;
        padding: 0;
        list-style: none;
    }
}

/* CSS */
nav { background-color: yellow; }

nav ul { margin: 0; padding: 0; list-style: none; }

Extends/Inheritance

.message {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
}

.success {
  @extend .message;
  border-color: green;
}

.error {
  @extend .message;
  border-color: red;
} 
      
/* CSS */
.success {border: 1px solid #ccc; padding: 10px; color: #333; border-color: green;}         
       
This is one of the most useful features of Sass. Using @extend lets you share a set of CSS properties from one selector to another. It helps keep your Sass very DRY.

Mixins

@mixin border-radius($radius) {
  -webkit-border-radius: $radius;
     -moz-border-radius: $radius;
      -ms-border-radius: $radius;
          border-radius: $radius;
}

.box { @include border-radius(10px); }

/* CSS */
.box {
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  -ms-border-radius: 10px;
  border-radius: 10px;
}

Functions

$col-count: 12;
 
@function col-pct($columns) {
    @return unquote((100/$col-count)*$columns+"%");
}
   
.col-6 { width: col-pct(6);}
   
/* CSS */
.col-6 { width: 50%; }       
    

(100 ÷ 12) = 8.333 × 6 = 50%

function returns a value.

Better tools, still problems

An example

<div class="restaurant-list">
    <h2>[Title]</h2>
    <ul>
        <li>[Restaurant item]</li>
    </ul>
</div>

/* SASS */
.restaurant-list {
    h2 { Styles.... }
    ul { More styles...}
        li { Even more styles... }
        li:nth-child(1) { Special styles... }
    }
}
 

The Cascade was the problem!

An example showing typical but simplified markup. Explain the syntax. Explain the good intentions of consistent default styling on html tags. Having to over ride them, and then introduce a new <ul> element into the mix...

Becoming a problem to maintain and understand...

Naming conventions

BEM syntax

  • Block
  • Element
  • Modifier
.restaurant-list {} /* Block */
.restaurant-list__title {} /* Element */
.restuarant-list__title--blue {} /* Modifier */
        
BEM to the rescue! Block: Standalone entity that is meaningful on its own. Element: Parts of a block and have no standalone meaning. They are semantically tied to its block. Modifier: Flags on blocks or elements. Use them to change appearance or behavior.

BEM advantages

<div class="restaurant-list">
    <h2 class="restaurant-list__title">[Title]</h2>
    <ul>
        <li class="restaurant-item">[Restaurant item]</li>
    </ul>
</div>

/* SASS */
.restaurant-list {} /* Block */
.restaurant-list__title {} /* Element */
.restuarant-list__title--blue {} /* Modifier */
.restaurant-item {} /* Block */
        
  • Mark-up independant
  • Easy to read just from the html
  • Standard convention
  • Ease of update and removal
Advantages: No overriding default styles. logical to read. Team members can read and understand. Well isolated and can be updated/removed with safety.
Frameworks. Large scale such as the two most popular, Bootstrap and Foundation, or smaller styles only such as Bourbon or hardcore using compass.

Opacity and Shadows

Embossed

 

Opacity
#embossed h1 { 
    text-shadow: 
       -2px -2px 2px #fff, 
        2px 2px 2px #000; 
}

#opacity h1 {
    opacity: 0.5;
}

Text shadow. As can be seen, we are appling two shadows to this h1, an inner and outer shadow to create this embossed effect.

Opacity. The colour of the text is white, overlapping the green box.

Transitions & Transforms

#box {
    transition: 
        width 2s, 
        height 2s, 
        background-color 2s, 
        border-radius 2s, 
        transform 2s;
}

#box:hover {
    transform: rotate(180deg);
}

CSS3 transitions: allows you to change property values smoothly (from one value to another), over a given duration.

The transform property applies a 2D or 3D transformation to an element. This property allows you to rotate, scale, move, skew, etc., elements.

Animation

.bubble {
    animation: bubble1-h-movement 
    1s ease-in infinite;
}

@keyframes bubble1-h-movement {
    0% {
        margin-left: 80%;
    }
    100% {
        margin-left: -100%;
    }
}
The animation property in CSS can be used to animate many other CSS properties such as color, background-color, height, or width. Each animation needs to be defined with the @keyframes at-rule which is then called with the animation property.

Shapes

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium et illo cupiditate veniam deleniti quos a nulla unde, at fuga dolor voluptatem, asperiores officia doloremque aspernatur soluta! Dignissimos, atque, totam! Vero perspiciatis sit et quisquam, explicabo velit temporibus dignissimos atque eveniet eius ipsum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi nobis, sint doloremque vitae eius sunt nam iste ducimus quos necessitatibus commodi rerum vero a beatae, architecto pariatur fugit earum explicabo.

 

.mask {
    -webkit-clip-path: circle(160px at 32% 50.95%);
    -webkit-shape-outside: circle(160px at 32% 50.95%);
}
Css shapes and masks.

Filters

blur sepia grayscale
#filter-img {
    -webkit-filter: blur(10px);
    -webkit-filter: sepia(1);
    -webkit-filter: grayscale(1);
}

There are many CSS filters to choose from:

  • grayscale
  • blur
  • sepia
  • saturate
  • opacity
  • brightness
  • contrast
  • hue-rotate
  • invert

While each property value generally falls between 0 and 1, there are a few exceptions. The blur property uses a unit of pixels and can be any whole number, and the hue-rotate filter value is a whole number with a "deg" unit.

Layout

  • Flexible Box Layout Module
  • Grid Layout Module

W3C specs Exciting layout modules will solve many common headaches.

In the flex layout model, the children of a flex container can be laid out in any direction, and can “flex” their sizes, either growing to fill unused space or shrinking to avoid overflowing the parent. Both horizontal and vertical alignment of the children can be easily manipulated.

This CSS module defines a two-dimensional grid-based layout system, optimized for user interface design. In the grid layout model, the children of a grid container can be positioned into arbitrary slots in a flexible or fixed predefined layout grid.

Flex Box

Horizontal - Vertical
  • 1
  • 2 with some more content here.
  • 3
  • 4

Flex Box

            
                .flex-container {
                    display: flex;
                    flex-direction: row;
                    flex-wrap: nowrap;
                    justify-content: space-between;
                    align-items: stretch;
                    min-height: 500px;
                }
                
                .flex-child {
                    flex-grow: 1;
                    flex-basis: 0;
                }
            
        

Justifiy content: This defines the alignment along the main axis. It helps distribute extra free space left over when either all the flex items on a line are inflexible, or are flexible but have reached their maximum size. It also exerts some control over the alignment of items when they overflow the line.

align-items: This defines the default behaviour for how flex items are laid out along the cross axis on the current line.

flex grow: This defines the ability for a flex item to grow if necessary. It accepts a unitless value that serves as a proportion. It dictates what amount of the available space inside the flex container the item should take up.

flex-basis: This defines the default size of an element before the remaining space is distributed. If set to 0, the extra space around content isn't factored in.

Grid layout

  • A
  • B
  • C
  • D
<ul id="grid">
    <li class="a">A</li>
    ...
</ul>

/* CSS */
#grid {
    display: grid;
    grid-template-rows: auto auto;
    grid-template-columns: 50% 50%;
}
       
#grid .a {
    grid-row: 1 / 2;
    grid-column: 1 / 2;
}

chrome://flags/

Enable experimental Web Platform features

In summary...

  • Limitations in language have been addressed with precompilers.
  • Naming conventions help larger projects maintain the code base.
  • Frameworks help you get up and running quickly.
  • Exciting new modules help provide a richer interface.
  • Layout modules will finally help build complex layouts

Questions?

Homer Simpson - “Lord help me, I’m just not that bright.”Example of using CSS. Created by multiple markup.
The state of CSS By Martin Riley Current development of Cascading Style Sheets and development methodologies. They'll be hidden in your presentation, but you can see them if you open the speaker notes window (hit 's' on your keyboard).