css - gitlab · css clever use of selectors sometimes, careful choice of selectors can help avoid...

39
CSS CSS CSS is the style language for web pages CSS stylesheets example 1

Upload: others

Post on 20-Jul-2020

15 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

CSSCSS

CSS is the style language for web pages

CSS stylesheets example

1

Page 2: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

CSSCSSThe standard we will use for dealing with style in webpages is CSS = Cascading Style Sheets, even though it isnot XML ( XSL)

Although CSS is not very complex, it is quite detailed,and you need good reference sites for it, see:

the development tools in your browserW3C CSS siteCSS 2.2 Standard (& beyond)CSS-TricksCSS Zen Garden

2

Page 3: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

XSLXSLXSL is an XML-based stylesheet language for addingstyle to XML, and is used mainly for processing single-source documents

First you transform using XSLT, and then you outputusing XSL-FO

In my personal opinion, XSLT is the world's worstdeclarative programming language, so bad that it's easierto use (say) Java

At one time, it seemed that it might take over from CSSfor HTML pages, but the idea has been abandoned

2a

Page 4: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

CSS VersionsCSS VersionsVersion 2.2 is the most recent complete standard,referred to by the HTML5 standard, and version 3 is amodular "work in progress"

Since browser support is generally a bit patchy, the bestadvice is:

Don't worry about versions, just take each feature andcheck the browser support situation, e.g. using Can-I-use, and aim to degrade gracefully degrading

3

Page 5: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

Degrading GracefullyDegrading GracefullyA web page degrades gracefully if it works OK on olderbrowsers or versions, perhaps in an inferior way orwithout decoration or with something inessentialmissing, but making self contained sense and not givinga wrong impression

It is not gracefulnot graceful if the site doesn't work, or the visitorcan see that something is missing, or can't navigateproperly, or the site shows a complaint about the age ofthe browser, or an apology for not being able to showsomething

3a

Page 6: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

Linking to a StylesheetLinking to a StylesheetYou should link to a stylesheet using a relative or site-relative URL in a link element in the head

<<linklink relrel=="stylesheet""stylesheet" hrefhref=="/style/slides.css""/style/slides.css" /> />

This is the only right way to add style, but there are lotsof wrong or obsolete ways:

don't use old HTML don't use the style attribute don't use the style tag

4

Page 7: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

bad htmlbad html

bad htmlbad html

Don't Use Old HTMLDon't Use Old HTMLDon't use any obsolete tags or attributes from HTML4which are style related and deprecated:

<<font...font...>>......</</fontfont>>

<<bodybody colorcolor=="green""green">>......</</bodybody>>

Style should be completely separated out so, forexample, small-device 'browsers' can ignore it altogether

Validation should sort this out

4a

Page 8: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

bad htmlbad html

Don't Use the Style AttributeDon't Use the Style AttributeAt first it seems harmless to add style in attributes:

<<emem stylestyle=="color:red""color:red">>......</</emem>>

BUT: you can get into XML-compatibility trouble withcertain characters, you cause maintenance effort (styleis scattered, and not shared in just one place) and youmay develop a bad habit

For this course, you musn't do it. For the rest of yourlife, I suggest a very strict self-discipline: the secondtime you do it on the same page, move the style to astyle tag at the top of the page

4b

Page 9: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

bad htmlbad html

Don't use the Style TagDon't use the Style TagStyle tags are also somewhat dangerous, not a goodseparation of the style issue, and may lead to bad habits:

<<stylestyle>> emem { { colorcolor: red; } : red; } </</stylestyle>>

In this course, you mustn't do it. For the rest of yourlife, I suggest a very strict self-discipline. The secondtime you use a style tag on a page on your site, switchto using a stylesheet

4c

Page 10: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

csscss

Selectors, properties, valuesSelectors, properties, valuesA CSS rule selects some elements (nodes in the tree),then attaches a property with a given value to them

This example selects all <em>...</em> elements andadds a color property, with value red to them

emem { { colorcolor: red; }: red; }

And that is CSS in a nutshell!

Beware:Beware: although CSS supports /* ... */ comments,it doesn't support one-line // comments

5

Page 11: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

CascadingCascadingHow does the browser find the value of a property foran element? It uses a complex algorithm, using threehierarchies:

stylesheets: from newest to oldestelements: from current outwards to outermostspecificity: from most specific to most general

specificity and importance

Use your development browser to check which rules arebeing applied

6

Page 12: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

csscss

Specificity and importanceSpecificity and importanceMore specific rules override less specific ones, e.g. arule for a given element id overrides a rule for a givenclass, which overrides a rule for a given tag name,which overrides a global rule

You can also override the normal order of checking byadding !important to a rule; important userpreferences override important stylesheet rules whichoverride normal rules, e.g.

emem { { colorcolor: red : red !important!important; }; }

6a

Page 13: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

csscss

csscss

Multiple PropertiesMultiple PropertiesIf you want multiple properties to apply, you can do itin one of two ways:

emem { { colorcolor: red; : red; font-weightfont-weight: bold; }: bold; }

emem { { colorcolor: red; }: red; } emem { { font-weightfont-weight: bold; }: bold; }

The two rules can even be in different stylesheets, butremember that more specific rules override moregeneral rules

7

Page 14: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

csscss

SelectorsSelectorsYou can select elements based on tagname, attribute, id,class, context

inputinput[type=text][type=text] [tag and attribute value][tag and attribute value] buttonbutton#save#save [tag and id][tag and id] #save#save [just id][just id] codecode.java.java [tag and class][tag and class] .java.java [just class][just class] h2h2++pp [follow][follow] prepre>>codecode [child][child] trtr:nth-child(3):nth-child(3) [nth child - third row][nth child - third row] aa:hover:hover [when hovering][when hovering]

8

Page 15: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

csscss

csscss

Multiple selectorsMultiple selectorsYou can select multiple sets of elements at once

emem, , bb, , h2h2 { { colorcolor: red; } : red; } [with commas!][with commas!]

You can also specify a style for one type of elementinside another type, e.g. all em elements within an h2

h2h2 emem { { colorcolor: red; } : red; } [no commas!][no commas!]

These are very similar: beware confusion

9

Page 16: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

htmlhtml

csscss

MeaningMeaningThe ideal is to keep the HTML as meaningful as possible,e.g. class names should explain whywhy an element needs tolook different:

<<pp classclass=="angry""angry">>I hate fontsI hate fonts</</pp>> <<pp classclass=="signature""signature">>Ian HolyerIan Holyer</</pp>> <<pp classclass=="angry signature""angry signature">>Mr Red FaceMr Red Face</</pp>>

The stylesheet then changes the look to match:

.angry.angry { { colorcolor: red; }: red; }

.signature.signature { { text-aligntext-align: right; }: right; }

10

Page 17: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

csscss

Clever use of selectorsClever use of selectorsSometimes, careful choice of selectors can help avoidlittering the HTML with ids and classes, e.g. to make allthe entries in the third column of a particular tableright aligned:

tabletable#stats#stats tdtd:nth-child(3):nth-child(3) { { text-aligntext-align:right;:right; }}

Try to find the best compromise between (a) HTML driving CSS, and (b) CSS navigating HTML

11

Page 18: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

bad htmlbad html

htmlhtml

Leftover Style TagsLeftover Style TagsTags like <i>, <b>, <tt> are really style tags

Often <em>, <strong>, <dfn>, <var>, <cite>,<q>, <code>, <kbd>, <samp> are better. E.g.:

<<ii>>CSSCSS</</ii>> is is <<ii>>veryvery</</ii>> easy... easy...

Later, you may want definitions to look different fromemphasis, which will be easier if you have written:

<<dfndfn>>CSSCSS</</dfndfn>> is is <<emem>>veryvery</</emem>> easy... easy...

12

Page 19: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

Range of PropertiesRange of PropertiesProperties that can be affected using CSS include:

sizes and positionsmargins, borders and paddingcolours and backgroundsfonts and texttableslistsprinting

A lot of these involve specifying numbers and choosingunits for them

13

Page 20: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

UnitsUnitsOne general issue that a lot of properties have incommon is units, for example, if you want to changefont size:

Browser Units (bad) Absolute Units (bad) Relative Units (bad) Relative Units (good)

The summary is that ems or percentages are best forfont sizes

14

Page 21: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

Browser UnitsBrowser UnitsThere are "browser" units xx-small, x-small,small, medium, large, x-large, xx-large andrelative browser units smaller, larger

Beware saying "browser defaults look too big, I'll usesmaller", because that is just in youryour environment withyouryour eyesight, it should be the visitor'svisitor's choice

Browsers disagree strongly over the size ratios, so theseunits are not recommended anyway

14a

Page 22: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

Absolute UnitsAbsolute UnitsThere are absolute units: inches, centimeters,millimeters, points (1/72 in) and picas (12/72 in)

font-size: 12pt; (in, cm, mm, pt, pc)font-size: 12pt; (in, cm, mm, pt, pc)

These may be OK for printing, but they are useless onscreen, because browsers would need to know people'smonitor resolutions, and they don't (they guess verybadly)

So absolute units are not recommended

14b

Page 23: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

Bad Relative UnitsBad Relative UnitsThere are relative units px (pixels), and ex (height ofletter x)

Using pixels provides good scaling across devices (exceptprinters!) BUT then the text doesn't scale when thevisitor changes the default text size

Browsers can't accurately detect the real height of theletter x, they guess badly, so ex shouldn't be used

14c

Page 24: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

Good Relative UnitsGood Relative UnitsFinally there are relative units em (width of letter M),and % (percentage of current value)

For text, em and % are the same (1em = 100% = currentfont size), for example:

h2h2 { { font-sizefont-size: : 2em2em; }; }

For parameters other than text, ems allow lengthsrelative to font size

Percentages have to be checked to see what they arepercentages of

14d

Page 25: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

csscss

ColoursColoursThe first rule of colour in CSS is to spell it color

A second rule is: if you change the colour of anything,take full control and specify the colour of everything(otherwise, your text colour may match your visitor'schosen background colour)

Here are some ways of specifying red:

colorcolor:rgb(255:rgb(255,0,0); ,0,0); [BEST, 0 to 255][BEST, 0 to 255] colorcolor:rgb(100:rgb(100%,0%,0%); %,0%,0%); [approximate, 100% = 255][approximate, 100% = 255] colorcolor::#ff0000#ff0000; ; [rrggbb hex][rrggbb hex] colorcolor::#f00#f00; ; [rgb hex, x means xx][rgb hex, x means xx] colorcolor:red:red; ; [only 17 standard names][only 17 standard names]

15

Page 26: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

bad cssbad css

FontsFontsGraphic designers love to control fonts:

pp { { font-familyfont-family: Arial; }: Arial; }

But Arial is a Windows font, so use:

pp { { font-familyfont-family: Arial,Helvetica,FreeSans,sans-serif; }: Arial,Helvetica,FreeSans,sans-serif; }

This gives choices in preference order, ending with afamily group which all browsers should support

What if you need the samesame font on all platforms (e.g.these slides, where the metrics matter)?

16

Page 27: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

htmlhtml

csscss

Web fontsWeb fontsSuppose you choose Molengo from Google Fonts

You can link live to Google's CDN (perhaps with aprotocol-relative URL):

<<linklink relrel=='stylesheet''stylesheet' hrefhref=='//fonts.googleapis.com/css?family=Molengo''//fonts.googleapis.com/css?family=Molengo' /> />

pp { { font-familyfont-family: Molengo; }: Molengo; }

There are more font details to worry about

17

Page 28: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

csscss

Web font detailsWeb font detailsIf you have a special need for a self-contained site, youcan download fonts:

@@font-facefont-face { { font-familyfont-family:Molengo; :Molengo; srcsrc::urlurl(('/fonts/Molengo.ttf''/fonts/Molengo.ttf'); }); } pp { { font-familyfont-family: Molengo; }: Molengo; }

A browser may still display text differently, even if thefont is identical, e.g. because of sub-pixel rendering

Usually it doesn't matter, but e.g. for these slides, someJavaScript is used to change the font size of programfragments

17a

Page 29: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

The Box ModelThe Box ModelLayout uses the box model, often visualized in browserdevelopment tools:

An element has width, height, padding, border, margin,all fully controllable

There are also box-sizing and flex properties formore sophisticated uses

18

Page 30: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

ComplexityComplexityEven using developer tools, it can be hard to work outwhat is going on:

HeadingHeading

This page has body then header, and a redbackground showing an unwanted body/header gap

There is no margin, border, or padding on body/header,but h2 has a margin which extends above the header

Solution: remove h2's top margin, or set overflow tohidden on the header

19

Page 31: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

csscss

DefaultsDefaultsThe appearance of elements is controlled almostentirely by CSS

For example h2 headings are defined by:

h2h2 { { displaydisplay: block;: block; font-sizefont-size: : 1.5em1.5em;; font-weightfont-weight: bold;: bold; marginmargin: : 0.83em0.83em 00;; }}

Check the defaults, in the HTML5 standard or browserdevelopment tools, before changing them in a stylesheet

20

Page 32: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

Vendor prefixesVendor prefixesExperimental new CSS features, implemented bybrowsers before the standard has settled, are sometimesmade available using vendor prefixes

For example, 3-D transforms, using the property nametransform, were available ahead of time as:

-webkit-transform (Chrome, Safari, Opera)-moz-transform (Firefox)-o-transform (old Opera)-ms-transform (IE)

Don't use them if obsolete, and use only temporarily

21

Page 33: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

Validating CSSValidating CSSYou can validate your CSS stylesheet by visiting theW3C CSS Validator site, or downloading their validator

Generally, it is far less important to validate CSS than tovalidate HTML

22

Page 34: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

Example Page DesignExample Page DesignLet's develop a simple page design with a header, twocolumns, and a footer, in a magazine style, targettingjust desktops, not mobiles

For mobiles, you need to use a responsive approach,switching to a single column for narrow windows,perhaps using a responsive framework

Our design will be fluid, but becoming fixed below areasonable minimum window width, to avoid problems

23

Page 35: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

csscss

csscss

The BodyThe BodyTo make a simple coloured header and footer for oursite style, first we have to make sure we can go right upto the edge of the page, by taking out margins orpadding on the body

bodybody { { paddingpadding: : 00; ; marginmargin: : 00; }; }

The body is given a minimum width, adjusted to whatthe content can stand. If the window goes narrowerthan that, the page format becomes fixed, with ahorizontal scrollbar

bodybody { { min-widthmin-width: : 640px640px; }; }

24

Page 36: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

csscss

csscss

Header and FooterHeader and FooterThe header and footer have no padding or margins,width 100% (of the body), background colour blue

headerheader, , footerfooter { { paddingpadding: : 00; ; marginmargin: : 00;; widthwidth: : 100%100%;; background-colorbackground-color: blue;: blue; }}

Each has its own fixed height, and the footer also clearsthe floats used for the two columns

headerheader { { heightheight: : 50px50px; }; } footerfooter { { heightheight: : 25px25px; ; clearclear: both; }: both; }

25

Page 37: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

csscss

ColumnsColumnsTo make two columns, we define two section classes,one for each column, and float them

sectionsection.left.left, , sectionsection.right.right { { widthwidth: : 44%44%; ; text-aligntext-align: justify;: justify; }} sectionsection.left.left { { floatfloat: left; : left; marginmargin: : 00 2%2% 00 4%4%; }; } sectionsection.right.right { { floatfloat: right; : right; marginmargin: : 00 4%4% 00 2%2%; }; }

The clear:both; in the footer makes sure thebrowser puts the footer underneath the floats, ratherthan trying to put it alongside them

26

Page 38: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

htmlhtml

Internet ExplorerInternet ExplorerWhen the page was written, it was worth supportingIE8, which doesn't support HTML5 at all

However, the main issue is just the new tags header,footer and section.

The standard polyfill for this is html5shiv.js

Instead of downloading it, we can just include it directlyfrom a CDN, cdnjs, using a protocol-relative URL

<!--[if IE]><!--[if IE]> <script src="//cdnjs.../html5shiv.min.js"<script src="//cdnjs.../html5shiv.min.js" ></script> ></script> <![endif]--><![endif]-->

27

Page 39: CSS - GitLab · css Clever use of selectors Sometimes, careful choice of selectors can help avoid littering the HTML with ids and classes, e.g. to make all the entries in the third

Headers and FootersHeaders and FootersA tough problem is sharing headers/footers:

stylesheets can't contain (much) HTML contentHTML5/CSS3 tricks aren't general enoughframes are obsolete; they spoil navigation etcSSI is platform dependentovernight programs spoil file properties

That leaves

copy-and-paste for static pages (not v. maintainable)server injection on deliveryJavaScript injection on arrival (maybe with AJAX)

28