Css Basics

150
CSS Created by Vladimir Zhydal

Transcript of Css Basics

CSSCreated by Vladimir Zhydal

WHAT?CSS is an acronym for Cascading Style Sheets.CSS is a style language that defines visual styles of HTMLdocuments.

WHY?Separation of presentation from markup.Cleaner code.Easier to manage style changes.

HISTORY1994

CSS was first proposed by Håkon Wium Lie.1996

CSS level 1 was published as a W3C Recommendation.1998

CSS level 2 was published as a W3C Recommendation.2011

CSS level 2.1 was published as a W3CRecommendation.

CSS3CSS 3 is divided into several separate documents called"modules".Each module adds functionality and/or replaces part ofthe CSS2.1 specification.

CSS4(THE GREAT RENAMING)

There is no such thing as CSS4.

SYNTAX

ANATOMY OF CSS RULE

GROUPING DECLARATIONSp color: red;

p font­size: 12px;

p line­height: 15px;

p color: red; font­size: 12px; line­height: 15px;

GROUPING SELECTORSh1 color: red; font­weight: bold;

h2 color: red; font­weight: bold;

h3 color: red; font­weight: bold;

h1, h2, h3 color: red; font­weight: bold;

COMMENTS/* Comment here */p margin: 1em; /* Comment here */ padding: 2em; /* color: white; */ background­color: blue;/*multi­linecomment here*/

APPLYING CSS

THREE WAYS TO ATTACHInline styleEmbeddedLinked

INLINE<h2 style="color: red;"></h2>

EMBEDDED<style>

</style>

h2 color: red;

LINKED<link rel="stylesheet" href="example.css" type="text/css">

SELECTORS

SELECTORSA CSS selector is the part of a CSS rule set that actually

selects the content.

SIMPLE SELECTORSPattern Meaning Level

* any element 2

E an element of type E 1

E.warning an E element whose class is "warning" 1

E#myid an E element with ID equal to "myid" 1

CLASS

can be used several times

ID

can only be used once

Use CSS classes where it’s possible, to make your stylesreusable on the page.

ATTRIBUTE SELECTORSPattern Meaning Level

E[foo] an E element with a "foo" attribute 2

E[foo="bar"] an E element whose "foo" attribute value isexactly equal to "bar"

2

E[foo~="bar"] an E element whose "foo" attribute value is a listof whitespace-separated values, one of which isexactly equal to "bar"

2

E[foo|="en"] an E element whose "foo" attribute has a hyphen-separated list of values beginning (from the left)with "en"

2

ATTRIBUTE SELECTORSPattern Meaning Level

E[foo^="bar"] an E element whose "foo" attribute value beginsexactly with the string "bar"

3

E[foo$="bar"] an E element whose "foo" attribute value endsexactly with the string "bar"

3

E[foo*="bar"] an E element whose "foo" attribute value containsthe substring "bar"

3

PSEUDO CLASSESPattern Meaning Level

E:linkE:visited

an E element being the source anchor of a hyperlink ofwhich the target is not yet visited (:link) or alreadyvisited (:visited)

1

E:activeE:hoverE:focus

an E element during certain user actions 1and2

E:target an E element being the target of the referring URI 3

PSEUDO CLASSESPattern Meaning Level

E:lang(fr) an element of type E in language "fr" (the documentlanguage specifies how language is determined)

2

E:enabledE:disabled

a user interface element E which is enabled ordisabled

3

E:checked a user interface element E which is checked (forinstance a radio-button or checkbox)

3

E:not(s) an E element that does not match simple selector s 3

PSEUDO CLASSES(STRUCTURAL)

Pattern Meaning Level

E:root an E element, root of the document 3

E:nth-child(n)

an E element, the n-th child of its parent 3

E:nth-last-child(n)

an E element, the n-th child of its parent, countingfrom the last one

3

E:nth-of-type(n)

an E element, the n-th sibling of its type 3

PSEUDO CLASSES(STRUCTURAL)

Pattern Meaning Level

E:nth-last-of-type(n)

an E element, the n-th sibling of its type, countingfrom the last one

3

E:first-child an E element, first child of its parent 2

E:last-child an E element, last child of its parent 3

E:first-of-type an E element, first sibling of its type 3

PSEUDO CLASSES(STRUCTURAL)

Pattern Meaning Level

E:last-of-type

an E element, last sibling of its type 3

E:only-child an E element, only child of its parent 3

E:only-of-type

an E element, only sibling of its type 3

E:empty an E element that has no children (including textnodes)

3

PSEUDO ELEMENTSPattern Meaning Level

E::first-line the first formatted line of an E element 1

E::first-letter the first formatted letter of an E element 1

E::before generated content before an E element 2

E::after generated content after an E element 2

COMBINATORSPattern Meaning Level

E F an F element descendant of an E element 1

E > F an F element child of an E element 2

E + F an F element immediately preceded by an E element 2

E ~ F an F element preceded by an E element 3

THE KEY SELECTORThe key selector is the right-most part of a larger CSS

selector. This is what the user agent looks for first.

SELECTOR MATCHING

VALUE PROCESSING

VALUE PROCESSINGA user agent must assign a value to every property that

applies to the target media type to every box in theformatting structure.

CALCULATIONCollecting all the declared values applied to an element.Cascading yields the cascaded value.Defaulting yields the specified value.Resolving value dependencies yields the computed value.Formatting the document yields the used value.Transforming to the actual value based on constraints ofthe display environment.

CALCULATION EXAMPLESProperty Winning

declarationCascadedvalue

Specified value Computedvalue

Usedvalue

Actualvalue

font-size font-size:1.2em

1.2em 1.2em 14.1px 14.1px 14px

width width: 80% 80% 80% 80% 354.2px 354px

width width: auto auto auto auto 134px 134px

height height: auto auto auto auto 176px 176px

page-break-after

(none) (none) auto (initial value) auto auto auto

FILTERING

FILTERINGIn order to find the declared values, user agents must first

identify all declarations that apply to each element.

FILTERINGA declaration applies to an element if:

It belongs to a style sheet that currently applies to thisdocument.It is not qualified by a conditional rule with a falsecondition.It belongs to a style rule whose selector matches theelement.It is syntactically valid: the declaration’s property is aknown property name, and the declaration’s valuematches the syntax for that property.

CASCADING

CASCADINGThe cascade takes a unordered list of declared values for a

given property on a given element, sorts them by theirdeclaration’s precedence, and outputs a single cascaded

value.

CASCADING ORIGINSAuthorUserUser agent

USER AGENT STYLE SHEETUser agent applies style sheets to all web documents. These

are referred to as a “default” user agent style sheet.

USER STYLE SHEETSMost user agents allow user to apply their own style sheets

within the user agent.

AUTHOR STYLES SHEETSWeb authors can apply one or more style sheets to an HTML

document.

CASCADING ORDERWHICH CSS RULES “WIN”?

There are four steps to determine which CSS rules will“win”.

STEP 1Gather all the declarations that apply to an element and

property from browser, author and user style sheets.

STEP 2Sort the gathered declarations according to:

originuser agentauthoruser

importancenormal!important

FROM LOWEST TO HIGHESTPRIORITY

Normal declarations in user agent style sheet.Normal declarations in user style sheet.Normal declarations in author style sheet.!important declarations in author style sheet.!important declaration in user style sheet.!important declaration in user agent style sheet.

STEP 3If declarations have the same origin or importance then the

declaration’s selectors need to be scored, to see whichdeclaration will “win”.

SELECTORS SPECIFICITY1. Inline style.2. Count the number of IDs.3. Count the number of

classes, attributes andpseudo-classes.

4. Count the number ofelement names or pseudo-elements.

A NOTE ON CONCATENATION“A” will always beat “B”, which will always beat “C”, which

will always beat “D”.

STEP 4If two declarations have the same importance, origin and

specify, the later specified declaration wins.

DEFAULTING

DEFAULTINGWhen the cascade does not result in a value, the specifiedvalue must be found some other way:

Inherited properties draw their defaults from theirparent element through inheritance.Other properties take their initial value.

INHERITANCEInheritance propagates property values from parent

elements to their children.

EXPLICIT DEFAULTINGResetting a Property: the initial keyword.Explicit Inheritance: the inherit keyword.Erasing All Declarations: the unset keyword.

BOX MODEL

BOX MODELThe CSS box model describes the rectangular boxes that are

generated for elements in the document tree and laid outaccording to the visual formatting model.

BOX DIMENSIONS

BOX EDGEScontent edge or inner edgepadding edgeborder edgemargin edge or outer edge

BOX-SIZINGcontent-boxpadding-boxborder-box

COLLAPSING MARGINSIn CSS, the adjoining margins of two or more boxes cancombine to form a single margin.

Margins that combine this way are said to collapse, andthe resulting combined margin is called a collapsedmargin.

VERTICAL MARGINS COLLAPSE(BASIC CASES)

Adjacent siblings.Parent and first/last child.Empty blocks.

HORIZONTAL MARGINS COLLAPSEDo not collapse in most cases...

COLLAPSING RESTRICTIONSOnly margins of block-level boxes can collapse.Margins of a floated box do not collapse with any othermargins.Margins of a box with ‘overflow’ other than ‘visible’ do notcollapse with its children's margins.Margins of an absolutely positioned box do not collapsewith any other margins.Margins of the root element's box do not collapse.

VISUAL FORMATTINGMODEL

VISUAL FORMATTING MODELThe CSS visual formatting model is the algorithm used to

process a document and display it on a visual media.

DEFINING BOXESbox dimensionsbox typethe positioning schemethe other elements in the treethe viewport size and positionintrinsic dimensions of contained imagesother external information

BOX GENERATIONThe part of the CSS visual formatting model.Creates boxes from the document's elements.

BOX TYPESAffect how the visual formatting is done.Depend of the value of the display CSS property.

BLOCK-LEVEL ELEMENTS ANDBLOCK BOXES

Visually formatted as a block.Intended to be vertically stacked.display: block, list-item, table.

BLOCK-LEVEL ELEMENTSParticipates in a block formatting context.Generates at least one block-level box (principal block-level box).

BLOCK CONTAINER BOXIs a box that contains only other block-level boxes, orcreates an inline formatting context.

A block-level box may also be a block container box.

BLOCK-LEVEL BOX

how the box will behave withits parents and sibling

BLOCK CONTAINER

how the box will interact withits descendants

BLOCK BOXES

Block-level boxes that also are block container boxes arecalled block boxes.

ANONYMOUS BLOCK BOXESSupplementary boxes.

Cannot be styled using CSS selectors.

Use the inherit value or the initial value of css properties.

ANONYMOUS BLOCK BOXES<div>Some inline text <p>followed by a paragraph</p> followed by more inline text.</div

INLINE-LEVEL ELEMENTS ANDINLINE BOXES

Distributed in lines with other inline-level content.

display: inline, inline-block, inline-table.

INLINE-LEVEL ELEMENTSGenerate inline-level boxes.

INLINE BOXES

Inline boxes are both inline-level boxes and boxes thatparticipate in their container's inline formatting context.

INLINE BOXESDIMENSIONS CALCULATION

widthdoesn't apply.

heightdoesn't apply, but the height of the box is given by the‘line-height’ property.

paddingonly left and right padding will have an effect.

marginonly left and right margin will have an effect.

ATOMIC INLINE-LEVEL BOXESInline-level boxes that do not participate in an inlineformatting context.

Are never split in several boxes.

Generated by: replaced inline-level elements, byelements with a calculated display value (inline-block or inline-table).

ATOMIC INLINE-LEVEL BOXES

The text in the span can besplit in several lines as it is an

inline box.

The text in the span cannot be split in several lines

as itis an inline-block box.

<style>

span

display: inline; /* default value*/

color: green;

</style>

<div>

The text in the span <span>can be split

in several lines as it</span> is an inline box.

</div>

<style>

span

display: inline­block;

color: green;

</style>

<div>

The text in the span <span>cannot be split

in several lines as it</span> is an inline­block box.

</div>

ANONYMOUS INLINE BOXESAny text that is directly contained inside a block containerelement (not inside an inline element).

Use the inherit value or the initial value of css properties.

ANONYMOUS INLINE BOXES<p>Some <em>emphasized</em> text</p>

OTHER TYPES OF BOXESLine boxes.Run-in boxes.Model-induced boxes.

POSITIONING SCHEMESNormal flow.Floats.Absolute positioning.

NORMAL FLOWBoxes are laid out one after the other

(vertically or horizontally).

NORMAL FLOWposition

staticrelative

floatnone

NORMAL FLOWSTATIC POSITIONING

The boxes are drawn at theexact position defined by the

normal flow layout.

RELATIVE POSITIONING

The boxes are drawn with anoffset defined by

the top, bottom, left and right CSSproperties.

FLOATSFloating boxes are positioned at the beginning or end ofthe current line.

Anything within the normal flow flows along the edge ofthe floating boxes.

FLOATSposition

staticrelative

floatleftright

THE CLEAR CSS PROPERTYSpecifies whether an element can be nextto floating elements that precede it or must be moveddown (cleared) below them.

Applies to both floating and non-floating elements.

BLOCK FORMATTING CONTEXTThe region in which:

the layout of block boxes occurs;floats interact with each other.

BLOCK FORMATTING CONTEXTCreated by:

the root element;floats;absolutely positioned elements;inline-blocks;table cells and table captions;elements where overflow has a value otherthan visible;flex boxes.

ABSOLUTE POSITIONINGBoxes are entirely removed from the flow.Boxes don't interact with the flow at all.Boxes positioned relative to their containing block.

CONTAINING BLOCKElement boxes are positioned within a formatting context,

which, by default, is provided by the box generated by aparent element.

CONTAINING BLOCKPOSITION: STATIC OR RELATIVE

The containing block is formed by the edge of the contentbox of the nearest ancestor elementwhose display property value is one of:

blockinline-blocklist-itemrun-intabletable-cell

CONTAINING BLOCKPOSITION: ABSOLUTE

The containing block is the nearest positioned ancestor(the nearest ancestor whose position property has one ofthe values absolute, fixed, or relative).The containing block is formed by the padding edge ofthat ancestor.

CONTAINING BLOCKPOSITION: FIXED

The containing block is the viewport (for continuousmedia) or the page box (for paged media).

THE STACKING CONTEXTBoxes are positioned in three dimensions.The third dimension is the z axis, which is perpendicularto the screen.

'Z-INDEX' PROPERTYFor a positioned box, the 'z-index' property specifies:

The stack level of the box in the current stackingcontext.Whether the box establishes a local stacking context.

FORMING OF A STACKING CONTEXTThe root element (HTML).Positioned (absolutely or relatively) with a z-index valueother than "auto".A flex item with a z-index value other than "auto".Elements with an opacity value less than 1.Elements with a transform value other than "none".Elements with a mix-blend-mode value other than"normal".Elements with a filter value other than "none".Elements with isolation set to "isolate".

STACKING CONTEXT LAYERSThe background and borders of the element thatestablishes the stacking context.The stacking contexts of descendants with negative stacklevels.Block-level descendants in the normal flow.Floated descendants and their contents.Inline-level descendants in the normal flow.Positioned descendants whose z-index is auto or 0.The stacking contexts of descendants with positive stacklevels.

STACKING CONTEXT(SUMMARY)

Positioning and a z-index value creates a stackingcontext.

Stacking contexts are hierarchical.

Each stacking context is completely independent from itssiblings.

THE GOLDEN RULE OF Z-INDEX“If you are using 3 digits z-index values, you are doing it

wrong.”

CSS AT-RULES

CSS AT-RULESAt-rules are instructions or directives to the CSS parser.

CSS AT-RULES@charset@import@media@page@font-face

@CHARSETThe @charset CSS at-rule specifies the characterencoding used in the style sheet.

This at-rule is useful when using non-ASCII characters insome CSS properties, like content.

@charset "UTF­8";@charset 'iso­8859­15';

@CHARSETSeveral ways to define the character encoding of a stylesheet:

The value of the Unicode byte-order character.The value given by the charset attribute of theContent-Type: HTTP header.The @charset CSS at-rule.The charset attribute of the <link> element. (obsoleted)The value of the <meta charset> in the document.

@IMPORTAllows to import style rules from other style sheets.

@import 'custom.css';@import url('landscape.css') screen and (orientation:landscape);

@MEDIAAssociates a set of nested statements, in a CSS block thatis delimited by curly braces, with a condition defined by amedia query.@media <media­query> /* media­specific rules */

@PAGEIs used to modify some CSS properties when printing adocument.@page :first margin: 1cm;@page :left margin: 1cm 3cm 1cm 1.5cm;@page :right margin: 1cm 3cm 1cm 1.5cm;

@FONT-FACEAllows authors to specify online fonts to display text ontheir web pages.@font­face font­family: "Bitstream Vera Serif Bold"; src: url("https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf"

CSS PROPERTIES

CSS PROPERTIESBox PropertiesLayout PropertiesList PropertiesTable PropertiesColor and BackgroundsTypographical PropertiesGenerated ContentUser Interface PropertiesPaged Media Properties

BOX PROPERTIESwidth (min/max), height (min/max), margin, padding,

border, outline

LAYOUT PROPERTIESdisplay, position, float, clear, visibility, top, right, bottom,

left, z-index, overflow, clip

LIST PROPERTIESlist-style-type, list-style-position, list-style-image

TABLE PROPERTIEStable-layout, border-collapse, border-spacing, empty-cells,

caption-side

COLOR AND BACKGROUNDPROPERTIES

color, background-color, background-image, background-repeat, background-position, background-attachment

TYPOGRAPHICAL PROPERTIESfont-family, font-size, font-weight, font-style, font-variant,letter-spacing, word-spacing, line-height, text-align, text-

decoration, text-indent, text-transform, text-shadow,vertical-align, white-space, direction

GENERATED CONTENT PROPERTIEScontent, counter-increment, counter-reset, quotes

USER INTERFACE PROPERTIEScursor

FONT

font: [font­style||font­variant||font­weight] font­size [/line­height] font­family | inherit

FONT<style>

</style>

<p class="font">Font</p>

.font

font: italic small­caps bold 50px/140% Helvetica, sans­serif;

BACKGROUNDCSS 2.1

background-colorbackground-imagebackground-repeatbackground-attachmentbackground-position

CSS 3

extends existing propertiesadds new properties:

background-originbackground-clipbackground-size

multiple-backgrounds

BACKGROUND<style>

</style>

<div class="background"></div>

.background

width: 500px;

height: 250px;

background­image: url('images/workshop/sheep.png'

url('images/workshop/betweengrassandsky.png');

background­position: center bottom, left top;

background­repeat: no­repeat;

GRADIENTDisplays smooth transitions between two or more specified

colors.

TRANSITIONAllows you to change property values smoothly over a given

duration.

ANIMATIONAllows animation of most HTML elements without using

JavaScript or Flash

TRANSFORMtranslatescalerotateskewperspectivematrix

BOX-SHADOWbox­shadow: none|h­shadow v­shadow blur spread color |inset|initial|inherit;

TEXT-SHADOW.neon

text­shadow:

0 0 10px #fff, 0 0 20px #fff,

0 0 30px #fff, 0 0 40px #ff00de,

0 0 70px #ff00de, 0 0 80px #ff00de,

0 0 100px #ff00de, 0 0 150px #ff00de;

.fire

text­shadow:

0 0 20px #fefcc9, 10px ­10px 30px #feec85,

­20px ­20px 40px #ffae34, 20px ­40px 50px #ec760c,

­20px ­60px 60px #cd4606, 0 ­80px 70px #973716,

10px ­90px 80px #451b0e;

BORDER-RADIUSborder-radius: 50px 0 0 50px;

border-radius: 40px 10px;

border-radius: 13em/3em;

border-radius: 13em 0.5em/1em 0.5em;

border-radius: 8px;

TEXT-OVERFLOWOne line text that should be…<style>

</style><p class="ellipsis">One line text that should be cut</p>

.ellipses overflow: hidden; white­space: nowrap; text­overflow: ellipsis;

COLUMNS<style> .columns column­count: 3; column­gap: 40px; </style><p class="columns">Some long text here...</p>

VENDOR-SPECIFIC PROPERTIES'-' + vendor specific identifier + '-' + meaningful name

Prefix Organisation

-ms- Microsoft

-moz- Mozilla Foundation(Gecko-based browsers)

-o- Opera Software

-webkit- Safari (and other WebKit-based browsers)

div ­webkit­border­radius: 3px; ­moz­border­radius: 3px; border­radius: 3px;

SHORTHAND PROPERTIESCSS properties that let you set the values of several other

CSS properties simultaneously.

SHORTHAND PROPERTIES(EDGE CASES)

A value which is not specified is set to its initial value. (itoverrides previously set values).

div background­color: red; background: url(images/bg.gif) no­repeat top right;

SHORTHAND PROPERTIES(EDGE CASES)

Only the individual properties values can inherit.

The keyword inherit can be applied to a property, but onlyas a whole, not as a keyword for one value or another.

.parent background: red;.child background: inherit;

SHORTHAND PROPERTIES(EDGE CASES)

Shorthand properties try not to force a specific order for thevalues of the properties they replace.

font: [font­style||font­variant||font­weight] font­size [/line­height] font­family | inherit

div font: italic bold 12pt/10pt serif

SHORTHAND PROPERTIES(PROPERTIES RELATED TO EDGES OF A BOX)

div padding: 10px;

div padding: 10px 20px;

div padding: 10px 20px 30px;

div padding: 10px 20px 30px 40px;

SHORTHAND PROPERTIES(PROPERTIES RELATED TO CORNERS OF A BOX)

div border­radius: 10px;

div border­radius: 10px 20px;

div border­radius: 10px 20px 30px;

div border­radius: 10px 20px 30px 40px

CSS UNITS

UNITSUnit Description

% percentage

em 1em is equal to the current font size. 2em means 2 times the size ofthe current font.

ex one ex is the x-height of a font (x-height is usually about half thefont-size)

px pixels (a dot on the computer screen)

UNITSUnit Description

pt point (1 pt is the same as 1/72 inch)

pc pica (1 pc is the same as 12 points)

in inch

cm centimeter

mm millimeter

UNITS RECOMMENDATIONS Recommended Occasional use Not recommended

Screen em, px, % ex pt, cm, mm, in, pc

Print em, cm, mm, in, pt, pc, % px, ex

MORE UNITS IN CSSUnit Description

rem is the font size of the root element of thedocument

vw 1/100th of the window's width

vh 1/100th of the window's height

RESOURCEShttp://www.w3.org/TR/CSS2/http://www.w3.org/Style/CSS/current-workhttps://developer.mozilla.org/en-US/docs/Web/Guide/CSShttps://css-tricks.com/almanac/http://reference.sitepoint.com/css