CSS - tutorial - 04 - values and units

Revision:


Content

Every property used in CSS has a value type defining the set of values for that property. Textual data types : custom-ident, pre-defined keywords as an ident, string, url Numbers, lengths, and percentages The color value specifies the color of an element feature. The image value specifies all the different types of image that can be used in CSS. The position value type represents a set of 2D coordinates, used to position an item Functional notation is a type of value that can represent more complex types. There are four viewport-based units in CSS: vh, vw, vmin and vmax. Recommended font-units New incoming CSS viewport units


Every property used in CSS has a value type defining the set of values for that property.

top

A value type in CSS is a way to define a collection of allowable values.

E.g. if you see <color> as valid you don't need to wonder which of the different types of color value can be used — keywords, hex values, rgb() functions, etc. You can use any available <color> values, assuming they are supported by your browser.

Depending on the property, the value can include a single integer or keyword, to a series of keywords and values with or without units. There are a common set of data types — values and units — that CSS properties accept.


Textual data types : custom-ident, pre-defined keywords as an ident, string, url

top

Text data types are either <string>, a quoted series of characters, or an <ident>, a "CSS Identifier" which is an unquoted string. A <string> must be quoted with either single or double quotes. CSS Identifiers, listed in the specifications as <ident> or <custom-ident>, must be unquoted.

In the CSS specifications, values that can be defined by the web developer - like keyframe animations, font-family names, or grid areas - are listed as a <custom-ident>, <string>, or both. When both quoted and unquoted user defined text values are permitted, the specification will list <custom-ident> | <string>, meaning quotes are optional, such as is the case with animation names.

Some text values are not valid if encompassed in quotes. For example, the value of grid-area can be a <custom-ident>, so if we had a grid area named content we would use it without quotes. In comparison, a data type that is a <string>, such as a string value of the content property, must be quoted.

Pre-defined keyword values

Pre-defined keywords are text values defined by the specification for that property. These keywords are also CSS Identifiers and are therefore used without quotes.

Keywords are more accurately described as identifiers, a special value that CSS understands. As such they are not quoted — they are not treated as strings.

there are places where you use strings in CSS; e.g. when specifying generated content. In this case, the value is quoted to demonstrate that it is a string.

All CSS properties accept the CSS-wide property values initial, inherit, unset, revert, and revert-layer, which explicitly specify defaulting behaviors.

initial - represents the value specified as the property's initial value.

inherit - represents the computed value of the property on the element's parent, provided it is inherited.

unset - acts as either inherit or initial, depending on whether the property is inherited or not.

revert - resets the property to its inherited value if it inherits from its parent or to the default value established by the user agent's stylesheet (or by user styles, if any exist).

revert-layer - rolls back the value of a property in a cascade layer to the value of the property in a CSS rule matching the element in a previous cascade layer. The value of the property with this keyword is recalculated as if no rules were specified on the target element in the current cascade layer.

A url() type uses functional notation, which accepts a <string> that is a URL.

This may be an absolute URL or a relative URL.

The parameter for url() can be either quoted or unquoted. If unquoted, it is parsed as a <url-token>, which has extra requirements including the escaping of certain characters.


Numbers, lengths, and percentages

top

There are various numeric value types. The following are all classed as numeric:

integer is a whole number, one or more decimal digits; e.g 1025, -55. An integer may be preceded by a + or - symbol, with no space between the symbol and the integer.

number represents a real number, which may or may not have a decimal point with a fractional component; e.g. 0.255, 128, or -1.2. Numbers may also be preceded by a + or - symbol.

dimension is a <number> with a unit attached to it; e.g. 45deg, 5s, or 10px. The attached unit identifier is case insensitive. There is never a space or any other characters between the number and the unit identifier: i.e. 1 cm is not valid. dimension is an umbrella category that includes the <length>, <angle>, <time>, <frequency>, <flex> and <resolution> types.

percentage represents a fraction of some other value; e.g., 50%. Percentage values are always relative to another quantity; e.g., an element's length is relative to its parent element's length.

Distance units: there are two types of lengths used in CSS: relative and absolute.

Absolute length units are not relative to anything else, and are generally considered to always be the same size.The follwing are all absolute length units:

cm (centimeters): 1cm = 37.8 px = 25.2/64 in

mm (millimeters): 1mm = 1/10th of a cm

Q (quarter-millimeters) = 1Q = 1/40th of a cm

in (inches): 1in = 2.54cm = 96px

pc (picas): 1pc = 1/6th of 1in

pt (points): 1pt = 1/72th of 1in

px (pixels): 1px = 1/96th of 1in

P.S. Most of these units are more useful when used for print, rather than screen output. The only value that is commonly used for screen output is px (pixels).

Relative length units are relative to something else, such as the size of the parent element's font or the size of the viewport. The benefit of using relative units is that the size of text or other elements can be scaled relative to everything else on the page. Some of the most useful units for web development are:

em: relative to the font size of the parent - in the case of typographical properties like font-size -, and to the font size of the element itself - in the case of other properties like width.

ex: relative to the x-height of the element's font.

ch: relative to the advance measure (width) of the glyph "0" of the element's font.

rem: relative to the font size of the root element.

lh: relative to the line height of the element.

vw: relative to 1% of the viewport's width.

vh: relative to 1% of the viewport's height.

vmin: relative to 1% of the viewport's smaller dimension.

vmax: relative to 1% of the viewport's larger dimension.

examples
I am 200px wide

I am 10vw wide

I am 10em wide
code:
                    <div class="wrapper">
                        <div class="boxes px">I am 200px wide</div><br>
                        <div class="boxes vw">I am 10vw wide</div><br>
                        <div class="boxes em">I am 10em wide</div>
                    </div>
                    <style>
                        .boxes{margin-left:10vw;border: 0.2vw solid blue}
                        .wrapper {font-size: 1em;}
                        .px {width: 200px;}
                        .vw {width: 10vw;}
                        .em {width: 10em; }
                    </style>
                

Other units: angle units, time units, frequency units, flex units, resilution units

Angle values are represented by the type <angle> and accept the following values:

deg - Degrees : there are 360 degrees in a full circle.

grad - Gradians : t1here are 400 gradians in a full circle.

rad - Radians : there are 2π radians in a full circle.

turn - Turns : there is 1 turn in a full circle.

Time values are represented by the type <time>. When including a time value, the unit identifier — the s or ms — is required. It accepts the following values:

s : seconds

ms : milliseconds. There are 1,000 milliseconds in a second.

Frequency values are represented by the type <frequency>. It accepts the following values:

Hz : Hertz : represents the number of occurrences per second.

kHz : KiloHertz : a kiloHertz is 1000 Hertz.

1Hz, which can also be written as 1hz or 1HZ, is one cycle per second.

Flex units are represented by the type <flex>. It accepts the following value:

fr : Flex : represents a flexible length within a grid container

Resolution units are represented by the type <resolution>. They represent the size of a single dot in a graphical representation, such as a screen, by indicating how many of these dots fit in a CSS inch, centimeter, or pixel. It accepts the following values:

dpi : dots per inch.

dpcm : dots per centimeter.

dppx, x : dots per px unit.

A percentage is, in a lot of cases, treated in the same way as a length.

Percentages, however, are always set relative to some other value. If you set an element's font-size as a percentage, it will be a percentage of the font-size of the element's parent; if you use a percentage for a width value, it will be a percentage of the width of the parent.

Some value types accept numbers without any unit added to them.

An example of a property which accepts a unitless number is the opacity property, which controls the opacity of an element (how transparent it is). This property accepts a number between 0 (fully transparent) and 1 (fully opaque).


The color value specifies the color of an element feature.

top

There are many ways to specify color in CSS, some of which are more recently implemented than others.

The same color values can be used everywhere in CSS, whether you are specifying text color, background color, or whatever else.

The standard color system available in modern computers supports 24-bit colors, which allows the display of about 16.7 million distinct colors via a combination of different red, green and blue channels with 256 different values per channel (256 x 256 x 256 = 16,777,216).

color words are a simple and understandable way of specifying color. There are a number of these keywords.

hexadecimal RGB values: each hex value consists of a hash/pound symbol (#) followed by six hexadecimal numbers, each of which can take one of 16 values between 0 and f (which represents 15) — so 0123456789abcdef. Each pair of values represents one of the channels — red, green and blue — and allows to specify any of the 256 available values for each (16 x 16 = 256). These values are a bit more complex and less easy to understand, but they are a lot more versatile than keywords.

RGB and RGBA values: an RGB value is a function — rgb() — which is given three parameters that represent the red, green, and blue channel values of the colors, in much the same way as hex values. The difference with hex RGB is that each channel is represented not by two hex digits, but by a decimal number between 0 and 255 — somewhat easier to understand.

RGBA colors work in exactly the same way as RGB colors, and so you can use any RGB values. However, there is a fourth value that represents the alpha channel of the color, which controls opacity. If you set this value to 0 it will make the color fully transparent, whereas 1 will make it fully opaque. Values in between give different levels of transparency.

HSL and HSLA values: instead of red, green, and blue values, the hsl() function accepts hue, saturation, and lightness values, which are used to distinguish between the 16.7 million colors, but in a different way:

hue: the base shade of the color; this takes a value between 0 and 360, representing the angles around a color wheel.
saturation: this takes a value from 0 to 100%, where 0 is no color (it will appear as a shade of grey), and 100% is full color saturation;
lightness: this takes a value from 0 to 100%, where 0 is no light (it will appear completely black) and 100% is full light (it will appear completely white)


The image value specifies all the different types of image that can be used in CSS.

top

The <image> value type is used wherever an image is a valid value. This can be an actual image file pointed to via a url() function, or a gradient.

examples
code:
                    <div>
                        <div class="box image"></div>
                        <div class="box gradient"></div>  
                    </div>
                    <style>
                    .box{margin-left:10vw; width: 30vw; height: 30vh; border: 0.2vw solid blue; }
                    .image {background-image: url('../pics/smiley.png'); }
                    .gradient {background-image: linear-gradient(45deg, rgba(119,0,255,1) 39%, 
                        rgba(0,212,155,1) 50%);
                    </style>
                

The position value type represents a set of 2D coordinates, used to position an item

top

It can take keywords - such as top, left, bottom, right, and center - to align items with specific bounds of a 2D box, along with lengths, which represent offsets from the top and left-hand edges of the box.

A typical position value consists of two values: the first sets the position horizontally, the second vertically. If you only specify values for one axis the other will default to center.

examples
code:
                    <div class="box position"></div> 
                    <style>
                        .box.position { height: 25vw; width: 40vw; background-image: url('../pics/smiley.png'); background-repeat: no-repeat; background-position: right 4vw;}
                    </style>
                

Functional notation is a type of value that can represent more complex types.

top

A function is a reusable section of code that can be run multiple times to complete a repetitive task with minimum effort on the part of both the developer and the computer.

Functions are usually associated with languages like JavaScript, Python, or C++, but they do exist in CSS too, as property values.

The syntax starts with the name of the function immediately followed by a left parenthesis ( followed by the argument(s) to the notation followed by a right parenthesis ).

Functions can take multiple arguments, which are formatted similarly to a CSS property value.

Some legacy functional notations such as rgba() use commas, but generally commas are only used to separate items in a list. If a comma is used to separate arguments, white space is optional before and after the comma.

Examples of CSS functions: rgb(), hsl(), url(), calc(), calc(), min(), max(), minmax(), clamp(), toggle(), attr(), etc.


There are four viewport-based units in CSS: vh, vw, vmin and vmax.

top

The viewport height (vh) unit is based on the height of the viewport. A value of 1vh is equal to 1% of the viewport height.

The viewport width (vw) unit is based on the width of the viewport. A value of 1vw is equal to 1% of the viewport width.

The viewport minimum (vmin) unit is based on the smaller dimension of the viewport. If the viewport height is smaller than the width, the value of 1vmin will be equal to 1% of the viewport height. Similarly, if the viewport width is smaller than the height, the value of 1vmin will be equal to 1% of the viewport width.

The viewport maximum (vmax) unit is based on the larger dimension of the viewport. If the viewport height is larger than the width, the value of 1vmax will be equal to 1% of viewport height. Similarly, if the viewport width is larger than the height, the value of 1vmax will be equal to 1% of hte viewport width.

The value of these units will be in different situations:

If the viewport is 1200px wide and 1000px high, the value of 10vw will be 120px and the value of 10vh will be 100px. Since the width of the viewport is greater than its height, the value of 10vmax will be 120px and the value of 10vmin will be 100px.

If the device is now rotated so that the viewport becomes 1000px wide and 1200px high, the value of 10vh will be 120px and the value of 10vw will be 100px. Interestingly, the value of 10vmax will still be 120px because it will now be determined based on the height of the viewport. Similarly, the value of 10vmin will still be 100px.

If you resize the browser window so that the viewport becomes 1000px wide and 800px high, the value of 10vh will become 80px and the value of 10vw will become 100px. Similarly, the value of 10vmax will become 100px and the value of 10vmin will become 80px.

Units like vmin and vmax need a recalculation, because the viewport width units include the scrollbar's width.


Recommended font-units

top

px as font-unit doesn't scale to proportion when the user zooms in or out in the browser.

rem stands for "root em", a unit of measurement that represents the "font size of the root element". This means that 1rem equals the font size of the "html element", which for most browsers has a default value of 16px.

Using rem can help ensure consistency of font size and spacing throughout the UI.

The main issue with using "rem" for font sizing is that the values are somewhat difficult to use.
Let's see an example of some common font sizes expressed in rem units, assuming, of course, that the base size is 16px:

10px = 0.625rem
12px = 0.75rem
14px = 0.875rem
16px = 1rem (base)
18px = 1.125rem
20px = 1.25rem
24px = 1.5rem
30px = 1.875rem
32px = 2rem

these values are not very convenient for making calculations.

em is proportional to the "font-size rule" of the nearest ancestor of an element.

To allow users to resize the text (in the browser menu), many developers use "em" instead of "pixels".
1em is equal to the "current font size". The default text size in browsers is 16px. So, the default size of 1em is 16px.
The size can be calculated from pixels to em using this formula: pixels/16=em.

% have almost similar behaviour like em. However, when you need relative sizing, "em" is more preferable.


New incoming CSS viewport units

top

the svh (smallest viewport height) unit reflects the smallest possible viewport height that is visible to the user. The smallest possible viewport height excludes all interface elements by the user agent. By default, the "vh unit" includes the address bar that comes with a mobile browser.

the lvh (largest viewport height) unit reflects the largest possible viewport height visible to the user.

the dvh (dynamic viewport height) unit reflects the current viewport height. This unit excludes the user agent's interface, unlike "unit vh", and updates as the current viewport height changes. The dvh unit reflects how much vertical viewport height the user agent's interface currently takes up. For instance, this will change as you scroll down a page on mobile, since the mobile URL bar moves out of your screen.

the svw (smallest viewport width) unit reflects the smallest possible viewport width that is visible to the user. This unit's value is static, so it will not be changed if the current viewport's width changes.

the lvw (largest viewport width) unit reflects the largest possible viewport width that is visible to the user. Like unit svw, this unit's value is static and will not change.

the dvw (dynamic viewport width) unit reflects the current viewport width that is visible to the user. This value is dynamic and will thus change according to the current viewport width.

the svmin (smallest viewport minimum) unit picks the smallest value between units svh and svw.

the lvmin (largest viewport minimum) unit picks the smallest value between units lvh and lvw.

the dvmin (dynamic viewport minimum) unit picks the smallest value between units dvh and dvw.

the svmax (smallest viewport maximum) unit picks the largest value between units svh and svw.

the lvmax (largest viewport maximum) unit picks the largest value between units lvh and lvw.

the dvmax (dynamic viewport maximum) unit picks the largest value between units dvh and dvw.

the vi unit refers to the viewport's size in the inline direction. For typical English text, the inline direction refers to the width; writing from left to right. However, for typical Chinese text layouts, the inline direction refers to the height; writing from top to bottom.

the svi unit refers to the viewport's smallest possible size in the inline direction.

the lvi unit refers to the viewport's largest possible size in the inline direction.

the dvi unit refers to the viewport's current possible size in the inline direction.

the vb unit refers to the viewport's size in the block direction. For typical English text, the block direction refers to the height; with lines wrapping from top to bottom. For typical Chinese text, the block direction refers to the width; wrapping lines from right to left.

the svb unit refers to the viewport's smallest possible dimension in the block direction.

the lvb unit refers to the viewport's largest possible dimension in the block direction.

the dvb unit refers to the viewport's current dimension in the block direction.

P.S. A recalculation is required for the new viewport units regarding the smallest and largest dimension, as they include the scrollbar's width: svmin, lvmin, dvmin, svmax, lvmax, and dvmax.