css fundamentals: selectors and properties

42
Pedro Valente | Ricardo Costa [pvalente|rcosta]@upt.pt 07/10/2015 - [week4] - TP Linguagens e Tecnologias Web CSS Fundamentals: Selectors and Properties IMP.GE.87.0 Licenciatura em Informática 2º Ano, 1º Semestre Licenciatura em Tecnologias e Sistemas de Informação 3º Ano, 1º Semestre

Upload: pedro-valente

Post on 10-Apr-2017

331 views

Category:

Education


1 download

TRANSCRIPT

Page 1: CSS Fundamentals: selectors and Properties

Pedro Valente | Ricardo Costa[pvalente|rcosta]@upt.pt

07/10/2015 - [week4] - TP

 

Linguagens e Tecnologias Web CSS Fundamentals: Selectors and Properties

IMP.GE.87.0

Licenciatura em Informática 2º Ano, 1º SemestreLicenciatura em Tecnologias e Sistemas de Informação 3º Ano, 1º Semestre

Page 2: CSS Fundamentals: selectors and Properties

Agenda

CSS – Cascading Style Sheets

CSS Rules

CSS Selectors

Inheritance & Cascade

2

Page 3: CSS Fundamentals: selectors and Properties

CSS

Cascading Style Sheets

3

Img src: http://blog.formstack.com

Page 4: CSS Fundamentals: selectors and Properties

4

The CSS Saga

Starts in 1994 Writers of web pages were complaining that

they didn’t have enough influence over how their pages looked…In fact, it has been a constant source of delight for me over the past year to get to continually tell hordes (literally) of people who want to -- strap yourselves in, here it comes -- control what their documents look like in ways that would be trivial in TeX, Microsoft Word, and every other common text processing environment: "Sorry, you're screwed."

This excerpt from a message sent to the www-talk mailing list early in 1994, gives a sense of the tensions between authors and implementers

More info: http://www.w3.org/Style/LieBos2e/history/

Page 5: CSS Fundamentals: selectors and Properties

Fundamentals

Separation of document structure from the document’s layout (also been a goal of HTML from its inception in 1990)

Tim Berners-Lee wrote his NeXT browser/editor as being possible to determine the style of a simple style sheet…• …but he didn´t publish the syntax for the style sheet, considering is a matter for each browser

to decide how to best display pages to its users!

Declaration-based language.

CSS applies presentation styles to the HTML content through rules.

• Should therefore be written after marking up the content.• Otherwise it leads to poor semantic HTML: constrained by the needs of the design rather than

the content.

CSS has a particular behaviour that allows a lot of flexibility in creating the presentation rules.

5 More info: Tim Berners-Lee's original World Wide Web browser

Page 6: CSS Fundamentals: selectors and Properties

Format

Textual Pure CSS files have the .css extension. The server sends CSS content with the

text/css MIME-TYPE. A page can have many CSS styles in many

CSS files. Comments can be added with:

/* this is a CSS comment */

6

http://www.w3schools.com/css/css_syntax.asphttp://www.w3.org/TR/css-syntax-3/https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax

Page 7: CSS Fundamentals: selectors and Properties

CSS3 Resources

Tutorials:http://docs.webplatform.org/wiki/css/tutorialshttp://www.css3maker.com/http://dev.opera.com/…more in the course’s website

Tools:http://jigsaw.w3.org/css-validator/http://www.cleancss.com/

7

Once again: there are no editors in the written tests!

Page 8: CSS Fundamentals: selectors and Properties

External file<link>Recommended solution. Best in nearly all situations.

Inside the <style> elementFor prototyping and rapid development in classes.

Inline in each elementShould be avoided at all costs.

8

How to use CSS?

Final ProjectYou must use external files

More info: Why Use CSS in Website Design

Page 9: CSS Fundamentals: selectors and Properties

External CSS file in HTML5

<!DOCTYPE html><html>

<head><meta charset='utf-8' /><title>Hello, World!</title><link rel='stylesheet'

href='styles.css' /></head><body>

Hello, World!</body>

</html>9

Both attributes are mandatory

Page 10: CSS Fundamentals: selectors and Properties

CSS RULES

10

Img src: http://learnwebcode.com

Page 11: CSS Fundamentals: selectors and Properties

Pseudo-code

p {color: blue;line-height: 2em;text-align: center;

}

CSS

For all paragraphs {Text colour : blue;Vertical spacing: large;Horizontal spacing: centre;

}

11

Rule syntax

More info: http://www.htmlhelp.com/reference/css/structure.html

Page 12: CSS Fundamentals: selectors and Properties

Rule syntax (cont.)

p{

color: blue;

line-height: 2em;

text-align: center;}

12

Selector

Declaration block

Property

Value

Page 13: CSS Fundamentals: selectors and Properties

Properties and values

There are hundreds of properties. Each has a domain of acceptable values. Some sets of values can be used in many

properties: color, background-color, border-color, etc. width, height, margin-top, padding-bottom, etc.

Some values can be used in a lot of properties: inherit, auto, none, etc.

For numeric values, it’s usually mandatory to include the unit (absolute or relative), except for the value 0: px, em, pt, rem, %, cm, etc.

13

Page 14: CSS Fundamentals: selectors and Properties

14

CSS Units – relative lengths

Unit Description

em Relative to the font-size of the element (2em means 2 times the size of the current font)

ex Relative to the x-height of the current font (rarely used)

ch Relative to width of the "0" (zero)

rem Relative to font-size of the root element

vw Relative to 1% of the width of the viewport*

vh Relative to 1% of the height of the viewport*

vmin Relative to 1% of viewport's* smaller dimension

vmax Relative to 1% of viewport's* larger dimension

%  

Relative length units specify a length relative to another length property. Relative length units scales better between different rendering mediums.

More info: http://www.w3schools.com/cssref/css_units.asp

Page 15: CSS Fundamentals: selectors and Properties

margin-top: 5px;margin-right: 10px;margin-bottom: 10%;margin-left: 0.75em;

padding, border, background, etc.

margin: 5px 10px 10% 0.75em;

15

Short-hand properties

top: 1st

right: 2nd

bottom: 3rd

left: 4th

Page 16: CSS Fundamentals: selectors and Properties

margin: 5px;

margin: 5px 10px;

margin: 5px 10px 15px;

All sides are set to 5px

Top/bottom are set to 5px Left/right are set to 10px

Top is set to 5px Left/right are set to 10px Bottom is set to 15px

16

Short-hand Properties (cont.)

Page 17: CSS Fundamentals: selectors and Properties

Colours (IE8 compatibility example) Names (16 colours) : red; Hexadecimal (4096 colours) : #f00; Hexadecimal (16.1m colours) : #ff0000; RGB (16.1m colours) : rgb(255, 0, 0); RGBA (16.1m colours + opacity) : rgba(255, 0, 0, 1);

To support IE8 only the first three colour formats should be used. The same property can be repeated with different colour formats because only the last one (recognised by the browser) will be used (see cascade).

17 More info: Color Picker Tool

Page 18: CSS Fundamentals: selectors and Properties

CSS SELECTORS

18

Img src: http://cscorner.dotnetheaven.netdna-cdn.com

Page 19: CSS Fundamentals: selectors and Properties

ELEMENT: Using only HTML elements.

CLASS: Using special names given to the class attribute of HTML elements.

ID: Using unique identifiers given to the id attribute of a single element.

p { … }h2 { … }input { … }

.special { … }

.example { … }

#hero { … }#user { … }

19

Types

Page 20: CSS Fundamentals: selectors and Properties

IDs and classes (HTML)

<h1 id=“hero”>Welcome!</h1><p class=“special”>This is blue text</p><p id=“user” class=“special”>This is blue text with blue border</p>

IDs: only 1 HTML element may have each id (per page). It’s recommended they start with a letter, have no spaces and

avoid special symbols. Classes:

It’s recommended they start with a letter, have no spaces and avoid special symbols.

20

Page 21: CSS Fundamentals: selectors and Properties

p {color: blue;

}

.special {color: blue;

}

If it’s necessary to apply the same style (property+value) using several selectors it’s possible to write all in the same rule, separating each selector with a comma:

p, .special {color: blue;

}21

Grouping selectors (Even of different types)

2 selectors separated by a comma

Page 22: CSS Fundamentals: selectors and Properties

Complicating Combining selectors

We may wish to apply styles to HTML elements depending on the existence or certain value of attributes:input[type='submit'] { ... }input[required] { ... }

Only apply a style when an element is a child of another:article p { … }div form input { … }

22

Page 23: CSS Fundamentals: selectors and Properties

Complicating Combining selectors (cont.) When an element is a first-level child of

another:article > p { … }div form > input { … }

When an element is a direct sibling of another:p + p { … }div form > label + input { … }

When an element is a sibling of another:p ~ p { … }div form > label ~ span { … }

23

Page 24: CSS Fundamentals: selectors and Properties

Complicating Combining selectors (cont.)

When an HTML element has a specific class or id:a#user { … }div.special { … }

When an HTML element with a specific class has a certain attribute and it’s a first-level child of another element which has a specific id:#user > .special[required] { … }

24

Page 25: CSS Fundamentals: selectors and Properties

Complicating Combining selectors (cont.)

Pseudo-classes: only apply a style rule when a certain state is achieved and can be combined with any type of selector: When the mouse is hovering over the element:

a:hover { … }

When the element with the specific class is selected:.bigbutton:active { … }

When the element with the specific id is the first child:li#me:first-child { … }

25

Page 26: CSS Fundamentals: selectors and Properties

tr:odd td { ... }tr:even td { ... }li:first-child { ... }li:nth-child(2n + 1) { ... }input:not([required]) { ... }

Regexa[href$='pdf'] { ... }a[href^='http'] { ... }

Pseudo-elements:

a::after {content: '(' attr(href)

')';}

Even more:::before::first-letter::first-line::selection

26

Other

Even with this dynamic functions, CSS is still NOT a programming language!

Page 27: CSS Fundamentals: selectors and Properties

Take note

The * selector should be used sparingly. Performance problems. The following is also bad:

div.grande fieldset * { … }

Pseudo-classes should also be used sparingly for the same reason.

The following selector is not only correct but also useful (why?): img#user { … }

27

Browsers parse selectors

right to left!

Page 28: CSS Fundamentals: selectors and Properties

INHERITANCE & CASCADE

28

Img src: https://upload.wikimedia.org

Page 29: CSS Fundamentals: selectors and Properties

Inheritance

In HTML elements are represented as as tree. The CSS styles of an element are, in most cases, inherited by its children.

This means that:<p>Hello <em>World</em>!</p>p { color: blue; }

Even the World word will be presented in blue, because the EM element is a child of the P element and the colour property in inherited.

29

Page 30: CSS Fundamentals: selectors and Properties

Inheritance

Some CSS properties are not inherited, for instance an element’s 50% width does not force its children to also have a 50% width. If this was true it would lead to the following situation:

Assuming the following tree: body > main > article > pbody { width: 50%; }

30

body

mainarticlep

The inherit value may be used in all properties to force inheritance and create the effect on the

left

Page 31: CSS Fundamentals: selectors and Properties

Inheritance

Even for inherited properties, it’s always possible to override the rules in the children when the inherited styles are not desired.

body {color: blue;

}

p {color: black;

}

31

Page 32: CSS Fundamentals: selectors and Properties

Cascade

While inheritance shows how a single rule can be applied to many different elements depending on the HTML tree…

…the cascade shows how two or more contradictory rules are applied by browsers.

The cascade is influenced by the following mechanisms: Importance Specificity Order

32

Page 33: CSS Fundamentals: selectors and Properties

Cascade – Importance

Depends on where and how the rule is defined: By the browser (called User Agent, or UA) By the user with normal declarations By the website (author) with normal

declarations By the website (author) with important

declarations By the user with important declarations

33

More importan

t

Page 34: CSS Fundamentals: selectors and Properties

Important declarations

The “!important” keyword may be placed at the end of a CSS style value to turn it into an important rule declaration:

p {color: green !important;

}

This should be avoided at all costs! It’s very easy to paint ourselves into a corner where it becomes nearly impossible to create more important rules even when they’re needed!

34

Page 35: CSS Fundamentals: selectors and Properties

Cascade – Specificity

Equation that chooses between two contradictory rules and applies one of them.

The equation has four terms (coloured different here). The browser resolves for each rule and then

compares the results. The comparison is performed left to right. Larger numeric values are more specific.

The most specific rule is the one that is applied by the browser.

35

, , ,More info: Inheritance and Cascading Styles in CSS ExplainedCSS: the cascade, specificity, and inheritance

Page 36: CSS Fundamentals: selectors and Properties

Left-most term, therefore contributes the most specificity.

This term can only have the values 0 (zero) or 1 (one).

Only inline styles (style attribute) resolve to 1 in this term. All others resolve to 0.

This is yet another reason why inline styles should never be used. Like the “!important” qualifier, it’s very easy to run out

of options to redefine inline styles because the specificity is too high.

36

Specificity Equation, , ,

Page 37: CSS Fundamentals: selectors and Properties

Second term, therefore contributes a lot of specificity.

This term has a numeric value equals to the number of IDs used in the selector.

For instance, the previous selector:#user > .special[required]

Resolves to 1: 1 id

37

Specificity Equation, , ,

Page 38: CSS Fundamentals: selectors and Properties

Third term, therefor contributes some specificity.

This term has a numeric value equals to the number of classes, pseudo-classes and attributes used in the selector.

For instance, the previous selector:#user > .special[required]

Resolves to 2: 1 class 1 attribute

38

Specificity Equation, , ,

Page 39: CSS Fundamentals: selectors and Properties

Right-most term, therefore contributes the least specificity.

This term has a numeric value equals to the number of elements and pseudo-elements used in the selector.

For instance, the previous selector:#user > .special[required]

Resolves to 0: No element or pseudo-element.

39

Specificity Equation, , ,

Page 40: CSS Fundamentals: selectors and Properties

Final Result

If we have the following rules:#user > .special[required] { color: blue; }body input:hover { color: red; }

If we have a textbox with the special class and the required Boolean attribute, what is the text’s colour when we hover the mouse over it?

40

Rule A Rule B

0 1 2 0 0 0 1 2

Try out: specificity calculator

Page 41: CSS Fundamentals: selectors and Properties

Cascade – Order

Once the importance and specificity is calculated, there’s one last mechanism to remove a tie between contradictory rules.

Rules declared afterwards in a single CSS file have precedence.

Rules declared in a CSS file loaded afterwards have precedence.

For this reason, CSS files should be loaded in order from most generic to most particular, for instance:<link rel=“stylesheet” href=“global.css” /><link rel=“stylesheet” href=“application.css” /><link rel=“stylesheet” href=“xmas.css” />

41

Page 42: CSS Fundamentals: selectors and Properties

IMP.GE.87.0