Difference between revisions of "CSS notes"

From Helpful
Jump to: navigation, search
m (flexbox)
m (Tables)
Line 417: Line 417:
Using tables for layouting was always considered somewhat dirty.
Using tables for layouting was always considered somewhat dirty,
and some people made an almost ideological point of avoiding it.
Before Grid, it was still sometimes still the more controlled ways of layouting,
but it's not a particularly reactive thing.
Yet, before Grid, it was still sometimes still the more controlled option to do more complex things.
(and some people made an almost ideological point of avoiding it)
It was never a particularly [[reactive]] thing.
Decent horizontally, more awkward vertically, distributing space is sometimes quite awkward,
Decent horizontally, more awkward vertically, distributing space is sometimes quite awkward,

Revision as of 02:00, 25 July 2021

Related to web development, hosting, and such: (See also the webdev category)
jQuery: Introduction, some basics, examples · plugin notes · unsorted
  • CSS notes

Server stuff:

Dynamic server stuff:


These are primarily notes
It won't be complete in any sense.
It exists to contain fragments of useful information.

Note that when most anyone or anything (including most browsers) mention CSS 2, they usually mean CSS 2.1 (CSS Level 2 Revision 1). This is not an insignificant detail, as 2.1's behaviour description includes corrections, and was current for a much longer time.

Things that can save a headache

CSS reset

This article/section is a stub — probably a pile of half-sorted notes, is not well-checked so may have incorrect bits. (Feel free to ignore, fix, or tell me)

Browsers have some default styling when it comes to margins, padding, etc, and this can vary between browsers.

When going for pixel-tight control, it helps to settle all of these (typically to zero) by default so that they are only non-zero when you said so. (Note: border-collapsing tables also help here)

It can also make sense to have a not-so-zero-looking CSS re-reset (particularly in some styles)

Additionally, it is useful to explicitly have default/fallback styles for a site, e.g

  • specifying site-wide background color and font
  • having border-collapsing tables by default
  • getting consistent form input styling (borders, padding, aligning, etc)

not selecting more than you want

avoiding name clashes

Class names like header are asking for trouble when merging different content.

Even when your site probably won't be, and is moderately easy to patch up then, javascript plugins may create elements with such classes, and it's why many opt for pseudo-namespaces to your selectors, e.g. appname-header.

If things are page-specific, you might also have some value in adding unique IDs to each page, so that you can do

body#about   div.section 
body#project div.section

This can also make sense when you want to allow templates fine control.

Avoiding anonymous descendant selectors

This article/section is a stub — probably a pile of half-sorted notes, is not well-checked so may have incorrect bits. (Feel free to ignore, fix, or tell me)

For example:

.details div { padding: .5em }

is problematic in that if you nest divs, each inherits its own .5em, and patching that up is a pain.

One way to day direct child is

.details>div  { padding: .5em }

...but in various cases, that inner div is also a meaningful one, so you may prefer:

.details div.section { padding: .5em }

...and generally rely on nested divs inherit a default (quite possibly 0px from your CSS reset).

Relayouting fun


Firefox will only show a scrollbar on your page when necessary, which means that if the page changes its contents, the scrollbars may be added later, which means a relayout which makes the page jump. If you figure the scrollbars will typically be useful for your page, you can force them with:

html { overflow:-moz-scrollbars-vertical; }

On sizes

This article/section is a stub — probably a pile of half-sorted notes, is not well-checked so may have incorrect bits. (Feel free to ignore, fix, or tell me)

On units:

  • px is pixels, which can be a bad idea for layouting or font sizing when you may have people with unusually high (or low) resolution, such as what Apple has dubbed retina displays.
  • em and ex are relative to the font size:
    • 1.0em is the font height, (Note this is different from e.g. TeX's definition), so scales along with client-based font resizing
    • 1.0ex is the height of a lowercase x, and varies per font (although not that much between most common web fonts). It's probably not as useful as em.
  •  % is relative to the size of the parent's bounding box size.
This interacts interestingly with padding and margins.
  • most others (pt, pc, mm, cm, in) are physical so depend on screen size and resolution.

I like to use em instead of pixel sizes or physical sizes, so that these things make sense on less-usual media as well. (it often has the added bonus of making sure that your layout makes sense when people resize the font).

See also:

Some layouting compared

Basics and more classical layouting











Font choice

This article/section is a stub — probably a pile of half-sorted notes, is not well-checked so may have incorrect bits. (Feel free to ignore, fix, or tell me)

On the concept of web-safe fonts

Other font-stack details

Glyph fallback

This article/section is a stub — probably a pile of half-sorted notes, is not well-checked so may have incorrect bits. (Feel free to ignore, fix, or tell me)
  • Glyphs are taken from the first font in the list that has it.(verify)
  • You can override specific ranges to come from one font
which is really the above behaviour plus saying "this font only has this"
  • Browsers may delay loading load fonts until more important things are satisfied
This matters in two ways I can think of
cases where this mixes glyphs from different fonts
cases where large fonts have to be downloaded.
some browsers won't display anything while loading a font. Others will display fallbacks first
This can matter when fonts are megabytes large
For simple western text, none of the configured fallback fonts may ever be loaded
If you have a generic family or web-safe font first, it'll probably cover more text faster(verify)
  • looks can matter to the order you specify.
Something like unifont has a simple version for a *lot* of things. Which is nice as a final fallback, but it's uglier than most any other font that has the glyph.
...but at the same time, putting it at the end for this reason may mean all the fonts on the way are downloaded, just to fall back to this one.

  • Places that can really see any character (such as unicode lookup tools) may wish to pay attention to serving fonts themselves, and to the order they are specified.
  • Services like Google Fonts can be nice
as a CDN-of-sorts for fonts
and it can be told serve a subset of glyphs from a large font.
  • If you have downloadable fonts (look for @font-face) in your font stack, you may as well first mention their name as if they are local fonts, for the few people who do have them installed, and fall back on the downloaded version.


CSS-capable browsers will usually take:

  • CSS that applies to all media (all), which seems the default
  • CSS that applies when rendering to specific media (like screen, print, projection, handheld, braille, tv, and a few others.

Note browsers may not support more than a few. Normal browsers seem to do print and screen.

Generally, for-media styling is either done by putting most of your styling in the omniscient all stylesheet and exceptions in each specific media stylesheet, or sometimes by making (or auto-generating) full stylesheets for each medium.


'print version'

While the below is handy to strip things you don't want in print, most people are not aware of such CSS details and will expect a print to look like the screen.

For this reason, it is generally clearer to offer a 'print version' link, whatever it actually does (remove styling from the current document, pop up a reduced version, etc).

different sheets

One solution is to add a print CSS file with exceptions that overrule the all sheet.

<link type="text/css" rel="stylesheet" media="print" href="print.css" />

...probably below your other links and <style> tags, since you're overriding.(verify)

If the CSS contains mostly overrides, the printed page will get styled the same way it normally would, except for the added rules, often stripping fancy/colored/imaged styling by generally setting, for example, color:black and background:none, border-color:black, and border-width:1px.

You could even do layouting differently in the printed version, which can handy if you want to print just the main content. Often enough it is easy enough to do this by hiding elements, though, which you probably want to do anyway.

It is also useful to hide things in printed versions of a webpage, like header images, various interactivity and navigation links (...that is not useful as context).

Perhaps the easiest way of doing this is with a simple class, say,
.noprint { display:none; visibility:collapse;}
added to said print.css, then setting that class on everything you don't want printed (possibly wrapped in a span or div)

You could also do the opposite - making a class that doesn't get shown on screen, but does get printed - this can be handy for semi-important things you would, on screen, handle in noticable tooltips.

There are other styles of doing the same as the print-sheet import above, including

<style type="text/css" media="print">@import "print.css";</style>
<style type="text/css">
@import url("print.css") print;

other media-specific specification

You can import a particular stylesheet to apply to a specific medium:

You can also specify rules for specific media in inline css, such as

@media print { body { font-size: 10pt } }
@media screen { body { font-size: 13px } }
@media screen, print { body { line-height: 1.2 } }

You can't do it on elements, though; the best you can do is using a class.


Lowering inline images

Inline icons and such often look a little too high. A class like like:

.imglower { vertical-align: -15%; }

...often goes a long way.

Paragraph indenting

text-indent applies to only the first line, so to indent only the first line:


To indent everything except the first line (note that you can use lists to do the same thing), try something like:

text-indent:-1.5em;  margin-left:1.5em;


The overflow (also separated into overflow-x and overflow-y) has four possible values:

  • visible: (default) content is not clipped
  • hidden: content is clipped
  • scroll: scrollbars are always added
  • auto: scrollbars are added only when there there is overflowing content (UAs have some choice, but that is the common behaviour)

See also W3/CSS2: Overflow and clipping

fixed-size containers with scrollbars:

To make a list of objects appear like it is in a list widget, you can fix the container's size and give it the CSS
. (Or overflow:scroll, but that always adds scrollbars, even when not necessary). Auto has horizontal and vertical scrollbars only when they are needed. Because of layouting works, that usually means the vertical one when necessary.

Fixed-size views that crop

Crop meaning text/content beyond a point (determined by layouting) just doesn't get displayed (like last.fm's track name labels). This can be useful to view up to a fixed size of something but not have it disturb layouting. One use is avoiding that long URLs (inherently non-line-breakable) break your layour widthwise.

It can be done in a few different ways that all involve

You would often set a width. You can set a height to, e.g. about 1.2em to display a single line, and you probably want to use line-height to increase the spacing between lines, to make sure you won't get stray ascenders from the line below.

whitespace behaviour like in <pre>

To get more literal whitespace treatment (newlines, spaces), set white-space:pre

You may also want to know about white-space:nowrap; it acts something like overflow:hidden.

image decorating e.g. a link

The following looks like the image is added as content:

.link-https {
  padding-right: 16px;
  background: url(lock_icon.gif) center right no-repeat;

(trick stolen from mediawiki)

::before and ::after

Mostly used with content to create a pseudoelement, something that renders before the actual content, e.g.

div.prepname::after {
  content: "Name: ";


.dquote::before { content: "«" }
.dquote::after  { content: "»" }

display:inline by default, but you can alter display:, position:, etc.

Note that since it is not part of the DOM, it's not as easy to manipulate directly.

In CSS2 it was :before, in CSS3 it became ::before but browsers should accept :before. (IE8 apparently doesn't understand ::before)


When you want border-like things that take no space, you can use

less configurable than borders.
basically just drawn on top, so will easily run into your content - keep them subtle.
  • borders, with box-sizing:border-box (border and padding are considered part of the content, unlike in the default css box model)

Note that when considering this to e.g. show widget focus, outline won't cause relayout, whereas borders easily might.

Per-page CSS in a single file

Sending CSS inline in a page each time can be a convenient way to control the scope at which that CSS applies, meaning you don't have to worry about collisions between short classnames.

However, centralizing CSS is useful, as you save some bandwidth if you avoid sending the CSS in each and every copy of the page. If you put it in a site's monolithic CSS file it will likely be cached too, meaning the CSS will load and apply faster.

A simple way to work around scoping problems is to manually create a scope per page by putting an id on each page's body. For example, a site's result.html could contain:

<body id="reshtml">

And the site css something like

#reshtml .header { }
#reshtml .results .row { }
#reshtml .results .row .name { }
/* ...etc */

text typesetting



  • left
  • right
  • center
  • justify (often called 'justified' or 'full')
  • inherit

CSS3 will have a more detailed text-justify



  • normal
  • inherit
  • a number, e.g. 2 for double-spacing or 1.5 for something less. (May be <1, but not <0)
  • a percentage (relative to font size(verify))
  • a specific length (e.g. in px or em)




  • auto (browser chooses)
  • default (non-special cursor; usually the arrow)
  • wait (often an hourglass)
  • text (select/edit I-bar, which is often the default on text)
  • pointer (often a hand)
  • help (often a questionmark)
  • crosshair

For interfaces:

  • move
  • e-resize, ne-resize, nw-resize, n-resize, se-resize, sw-resize, s-resize, w-resize

Non-standard (introduced in IE), not necessary supported:

  • progress (usually hourglass besides arrow)
  • all-scroll
  • col-resize, row-resize (think frame resizing)
  • no-drop, not-allowed (usually a circle with a bar through it)
  • url: an arbitrary image (one of the less supported ones, and there are varying extra browser-specific requirements)
  • vertical-text (rotated I-bar)

Quirksmode has a detailed list of what browsers support what cursor styles.

Vertical text


Sass, SCSS

Semantically Awesome Style Sheets (Sass)

There are two syntaxes:

  • SCSS (Sassy CSS)
extension, meaning that css is valid scss
.scss extension
  • indented syntax / Sass
uses indentation instead of brackets and newlines rather than semicolons
more concise
.sass extension

Both are more expressive syntaxes, that require translation into plain css.

Handiness they add includes:

  • reusing values through variable-like things
note that CSS3 has variables itself
  • reusing blocks of proprerties
@mixin and @include (note these can be parametrized)
or @extend (superclass style)
  • color-math like darken, lighten, saturate, complement [1]
  • @import is combined in the translation step, not a separate HTTP request as it is in plain CSS
also making it no-cost to organize large stylesheets into parts
deal with templates and predefined styles a little more flexibly
  • nested syntax, is sometimes more natural than css selectors

See also https://sass-lang.com/

Strict mode, quirks mode

the pain of vertical layouting

This article/section is a stub — probably a pile of half-sorted notes, is not well-checked so may have incorrect bits. (Feel free to ignore, fix, or tell me)

Sometimes you want a-full-screen layouting instead of scrolling-because-of-variable-content.

While 'relative to screen sizes' exists, but 'relative to containing element' only exists in absolute measurements, not percentages(verify).

This means dividing the screen is very hard to do neatly (though there are workarounds for two or three elements, mostly consisting of abusing margins on one or both sides as positioning).

It also seems impossible to scroll nested things when needed (overflow:auto style) for containers that are not absolutely sized, while relative sizing will almost as a rule break layouting as percentage refers to page size, not container size. This can in some cases be worked around using - ironically - tables.

Also, 100%-ing height tends to not work well. If you want to do this, make sure you specify a height (probably 100%) at all levels (apparently because if some level computes to none, all children will too(verify)).

Depending on the case, this may be doable enough, or impractical.

Incidentally, the same seems to apply to max-height tricks.

These days there are also viewport height, which does not require the size to be set throughout the tree.

box model

Refers to the way box sizes are calculated/rendered; see e.g. [2].

IE for a long time did not fully comply to those specs (they basically couldn't in the initial implementation of their rendering engine), and (for backwards compatibility) still does not do so in quirks mode.

Box model:


This article/section is a stub — probably a pile of half-sorted notes, is not well-checked so may have incorrect bits. (Feel free to ignore, fix, or tell me)

(Note that much of this was non-standard or did not exist before CSS/CSS2)

Conditional comments

Specifically, HTML comments that contain conditions that only IE on windows will use(verify), and are implicitly ignored by everything else, as they are actually inside delimited comments.

It is usually used to include an IE-specific stylesheet without having to implement browser detection via scripting.

Since this relies on features rather than bugs (unlike CSS syntax hacks and such), this is a robust way to include CSS that works around bugs in IE, and other IE-specific things.

For example, IE-in-general:

<!--[if IE]>
 <link rel="stylesheet" type="text/css" href="ie_workarounds.css" />

Specific versions (or many, e.g. <!--[if lte IE 6]>) of IE, for example those present in IE6 (and fixed in IE7).

<!--[if IE 6]>
 <link rel="stylesheet" type="text/css" href="ie6_workarounds.css" />

See also:


  • :hover (note that IE before 7 doesn't support this on non-links)
  • :active (note that this is not always supported on everything. Be careful when applying it on elements other than A, INPUT, BUTTON, and similar things)
  • :focus


CSS sprites

This article/section is a stub — probably a pile of half-sorted notes, is not well-checked so may have incorrect bits. (Feel free to ignore, fix, or tell me)

CSS sprites refer to using an image file to contain more than one logical image. Think, for example, of having an image store the normal, rollover, and clicked state for a starring system, button, or similar.

The largest upside is that you can store many buttons/states in a single file, reducing the amount of images that will have to be loaded for a web page, and thereby the load time through lag, apparent load time, and avoid things like late-loading hover states (although pre-loading images is not very hard either).

In the case of CSS, you include the same file repeatedly, an use styling (width, height, ) to create viewports of sorts so that each use actually shows the sub-image you want. This is usually done by exploiting the background property, specifically for background-position [3].

Preloading images

This article/section is a stub — probably a pile of half-sorted notes, is not well-checked so may have incorrect bits. (Feel free to ignore, fix, or tell me)

Image preload means that page items aren't randomly visually fast and slow to respond.

Common methods:

  • One common way is to pre-load images by using <img> tags that are not displayed. There are various ways of doing this, such as:
    • display:none on the images, or on a div around a few images, etc.
    • position a div containing img tags outside the window, and overflow:hidden on the containing element to avoid scrollbars
    • use background: with the transparent color, the image, no-repeat, and a position that means the image will not be visible.
  • Alternatively, you can use javascript. Preloading scripts often do the invisible DOM element thing, but can choose to delay it until after the page has loaded, to avoid slowing down the initial load. A downside is that it means that the paranoid script-disabling crowd will get no preload.

You usually want to stick pre-loading on the end of your page (elements at the end of the body, or onload scripting), since you probably want to minimize the effect on the initial load time. You're likely loading images that are only necessary for later interaction, and have enough imagery for the initial load anyway.