All notes
Css

# Syntax

## Three ways to insert CSS

### External stylesheet





### Internal stylesheet



<style>
body {
background-color: linen;
}

h1 {
color: maroon;
margin-left: 40px;
}
</style>


### Inline styles





## fallback

Some css features are not compatible across browsers, e.g. rgba() for IE8.

The old way for fixing this is using conditional comment:



<!--[if lte IE 8]>
<![endif]-->

// In modern.css we have:
.me {
color: rgba(0, 0, 0, 0.5);
}
// And in ie8only.css we have:
.me {
color: #ccc;
}


We can do this better using CSS fallback properties within a single CSS file, like this:


.me {
color: #ccc;
color: rgba(0, 0, 0, 0.5); // in IE 8 or older versions, because it’s an invalid value, the browser does nothing and still uses the first value, “#ccc.”
}


### Media query



:root {
--penguin-size: 300px;
--penguin-skin: gray;
--penguin-belly: white;
--penguin-beak: orange;
}

@media (max-width: 350px) {
:root {

--penguin-size: 200px;
--penguin-skin: black;

}
}


Width. This is probably the most important property, since it can be used to choose page layout - less columns for narrower screens and more columns for wider ones. The property accepts min/max prefixes, so we'd better add those to specify a width range.


<link rel="stylesheet" media="print and (min-width:25cm)" href="a.css" /> <!-- In HTML -->

/* In CSS. The {...} only works when the 3 conditions are met. */
@media screen and (min-width: 400px) and (max-width: 700px) {}

/* In CSS. Import the CSS file only when either the two conditions are met: screen and (min-width: 400px), */
/* or projection and (color). The comma denotes an 'or' logic. */
@import url(example.css) screen and (min-width: 400px), projection and (color);

Orientation. There are two values for this property: portrait an landscape. It is easy to distinguish: when the height is larger than or equal to the width, it's portrait, otherwise landscape.


@media all and (orientation:portrait) {...}

Color. It accepts min/max prefixes. Its value type is integer, which specifies the bit number per color component of the device. If the device is not color device, the value is 0. The example below express a style for all color devices.


@media all and (color) { … }
@media all and (min-color: 1) {...}


## units

Relative Lengths:

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

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

ch	Relative to width of the "0" (zero)
ic  Equal to the used advance measure of the "?" (CJK water ideograph, U+6C34)
ex	Relative to the x-height of the current font (rarely used)

lh  Equal to the computed value of the line-height property


Absolute Lengths:

cm	centimeters
mm	millimeters
in	inches (1in = 96px = 2.54cm)
px	pixels (1px = 1/96th of 1in)
pt	points (1pt = 1/72 of 1in)
pc	picas (1pc = 12 pt)


Pixels (px) are relative to the viewing device. For low-dpi devices, 1px is one device pixel (dot) of the display. For printers and high resolution screens 1px implies multiple device pixels.

## Variables, var()

Variables in CSS should be declared within a CSS selector that defines its scope. For a global scope you can use either the ":root" or the "body" selector.

The variable name must begin with two dashes (--) and is case sensitive!

The syntax of the var() function is as follows: var(custom-name, fallback_value).



:root {
--main-bg-color: coral;
}
#div1 {
background-color: var(--main-bg-color);
}
#div2 {
background-color: var(--main-bg-color);
}

<!-- ---------- Penguin example from freecodecamp -->

<style>
.penguin {

/* variables below */
--penguin-skin: gray;
--penguin-belly: white;
--penguin-beak: orange;
/* variables above */

position: relative;
margin: auto;
display: block;
margin-top: 5%;
width: 300px;
height: 300px;
}

.penguin-top {
top: 10%;
left: 25%;
background: var(--penguin-skin, gray);
width: 50%;
height: 45%;
}

.penguin-bottom {
top: 40%;
left: 23.5%;
background: var(--penguin-skin, gray);
width: 53%;
height: 45%;
}

.right-hand {
top: 0%;
left: -5%;
background: var(--penguin-skin, gray);
width: 30%;
height: 60%;
transform: rotate(45deg);
z-index: -1;
}

.left-hand {
top: 0%;
left: 75%;
background: var(--penguin-skin, gray);
width: 30%;
height: 60%;
transform: rotate(-45deg);
z-index: -1;
}

.right-cheek {
top: 15%;
left: 35%;
background: var(--penguin-belly, white);
width: 60%;
height: 70%;
}

.left-cheek {
top: 15%;
left: 5%;
background: var(--penguin-belly, white);
width: 60%;
height: 70%;
}

.belly {
top: 60%;
left: 2.5%;
background: var(--penguin-belly, white);
width: 95%;
height: 100%;
}

.right-feet {
top: 85%;
left: 60%;
background: var(--penguin-beak, orange);
width: 15%;
height: 30%;
transform: rotate(-80deg);
z-index: -2222;
}

.left-feet {
top: 85%;
left: 25%;
background: var(--penguin-beak, orange);
width: 15%;
height: 30%;
transform: rotate(80deg);
z-index: -2222;
}

.right-eye {
top: 45%;
left: 60%;
background: black;
width: 15%;
height: 17%;
}

.left-eye {
top: 45%;
left: 25%;
background: black;
width: 15%;
height: 17%;
}

.sparkle {
top: 25%;
left: 15%;
background: white;
width: 35%;
height: 35%;
}

.blush-right {
top: 65%;
left: 15%;
background: pink;
width: 15%;
height: 10%;
}

.blush-left {
top: 65%;
left: 70%;
background: pink;
width: 15%;
height: 10%;
}

.beak-top {
top: 60%;
left: 40%;
background: var(--penguin-beak, orange);
width: 20%;
height: 10%;
}

.beak-bottom {
top: 65%;
left: 42%;
background: var(--penguin-beak, orange);
width: 16%;
height: 10%;
}

body {
background:#c6faf1;
}

.penguin * {
position: absolute;
}
</style>
<div class="penguin">
<div class="penguin-bottom">
<div class="right-hand"></div>
<div class="left-hand"></div>
<div class="right-feet"></div>
<div class="left-feet"></div>
</div>
<div class="penguin-top">
<div class="right-cheek"></div>
<div class="left-cheek"></div>
<div class="belly"></div>
<div class="right-eye">
<div class="sparkle"></div>
</div>
<div class="left-eye">
<div class="sparkle"></div>
</div>
<div class="blush-right"></div>
<div class="blush-left"></div>
<div class="beak-top"></div>
<div class="beak-bottom"></div>
</div>
</div>


## Colors

### hsl()

Hue is what people generally think of as 'color'. If you picture a spectrum of colors starting with red on the left, moving through green in the middle, and blue on right, the hue is where a color fits along this line. In hsl(), hue uses a color wheel concept instead of the spectrum, where the angle of the color on the circle is given as a value between 0 and 360.

Saturation is the amount of gray in a color. A fully saturated color has no gray in it, and a minimally saturated color is almost completely gray. This is given as a percentage with 100% being fully saturated.

Lightness is the amount of white or black in a color. A percentage is given ranging from 0% (black) to 100% (white), where 50% is the normal color.

Here are a few examples of using hsl() with fully-saturated, normal lightness colors:

Color	HSL
red	hsl(0, 100%, 50%)
yellow	hsl(60, 100%, 50%)
green	hsl(120, 100%, 50%)
cyan	hsl(180, 100%, 50%)
blue	hsl(240, 100%, 50%)
magenta	hsl(300, 100%, 50%)


# Properties

## appearance

WARNING: IE doesn't support it! And Firefox has some problem with it!

The appearance property is used to display an element using a platform-native styling based on the users' operating system's theme.



.thing {
-webkit-appearance: value;
-moz-appearance:    value;
appearance:         value;
}

// inputs with a type=search in WebKit browsers by default have rounded corners and are very strict in what you can alter via CSS. If you don't want that styling, you can remove it in one fell swoop with appearance.

input[type=search] {
-webkit-appearance: none;
}

// Or you could take a input with type=text and just make it look like a search input:

input[type=text] {
-webkit-appearance: searchfield;
}


## background

### background-image

By default, a background-image is placed at the top-left corner of an element, and repeated both vertically and horizontally.

The background of an element is the total size of the element, including padding and border (but not the margin).

Always set a background-color to be used if the image is unavailable.



// Sets two background images for the <body> element. Let the first image appear only once (with no-repeat), and let the second image be repeated:

body {
background-image: url("img_tree.gif"), url("paper.gif");
background-repeat: no-repeat, repeat;
background-color: #cccccc;
}

Sets a linear-gradient (two colors) as a background image for a <div> element:

height: 200px;
background-color: #cccccc;
background-image: linear-gradient(red, yellow); // From red to yellow.
}

height: 200px;
background-color: #cccccc;
background-image: linear-gradient(red, yellow, green); // From red to yellow, then to green.
}

height: 200px;
background-color: #cccccc;
background-image: repeating-linear-gradient(red, yellow 10%, green 20%); // red-yellow accounts for 10% height, r-y-g accounts for 20% height, then repeat, which means it has 5 copies (5 x 20% = 100%).
}

height: 200px;
background-color: #cccccc;
}


### background-size

auto	Default value. The background image is displayed in its original size.
cover   Resize the background image to cover the entire container, even if it has to stretch the image or cut a little bit off one of the edges.
contain Resize the background image to make sure the image is fully visible.


html {
background: url(greatimage.jpg);
background-size: 300px 100px;
}

html {
background: url(greatimage.jpg), url(wonderfulimage.jpg);
background-size: 300px 100px, cover;
/* first image is 300x100, second image covers the whole area */
}

#example1 {
border: 2px solid black;
background: url(img_tree.gif), url(mountain.jpg);
background-repeat: no-repeat;
background-size: contain, cover;
}
/* img_tree is displayed fully, and mountain.jpg is displayed to span the whole background. */


## clear

The clear property specifies which side(s) of an element other floating elements are not allowed.

clear: none(default)|left|right|both|initial|inherit.

## content

content: normal|none|counter|attr|string|open-quote|close-quote|no-open-quote|no-close-quote|url|initial|inherit;

• counter: Sets the content as a counter
• attr(attribute): Sets the content as one of the selector's attribute
• string: Sets the content to the text you specify
• url(url): Sets the content to be some kind of media (an image, a sound, a video, etc.)

#### Example: attr


/* <a href="http://www.w3schools.com">W3Schools</a> will becomes:
W3Schools (http://www.w3schools.com)
*/
a:after {
content: " (" attr(href) ")";
}

#### Example: counter


div {
counter-reset: myIndex;
}

p {
counter-increment: myIndex;
}

p:before {
content:counter(myIndex);
}


## counter-reset, counter-increment

counter-increment: none|id|initial|inherit;
The default increment is 1.
0 or negative values, are allowed.
counter-reset: none|name number|initial|inherit;
The default reset value is 0.


/* Auto numbering on headings. */
h1 {
counter-reset: h2;
}
h2 {
counter-reset: h3;
}
h3 {
counter-reset: h4;
}
h4 {
counter-reset: h5;
}

h2:before {
counter-increment: h2;
content: counter(h2) ". ";
}
h3:before {
counter-increment: h3;
content: counter(h2)"." counter(h3) ". ";
}
h4:before {
counter-increment: h4;
content: counter(h2)"." counter(h3)"." counter(h4) ". ";
}
h5:before {
counter-increment: h5;
content: counter(h2)"." counter(h3)"."counter(h4)"." counter(h5) ". ";
}


## cursor

It controls what the mouse cursor will look like when it is located over the element in which this property is set.


.auto            { cursor: auto; }
.default         { cursor: default; }
.none            { cursor: none; }

.help            { cursor: help; }
.pointer         { cursor: pointer; }
.progress        { cursor: progress; }
.wait            { cursor: wait; }
.cell            { cursor: cell; }
.crosshair       { cursor: crosshair; }
.text            { cursor: text; }
.vertical-text   { cursor: vertical-text; }
.alias           { cursor: alias; }
.copy            { cursor: copy; }
.move            { cursor: move; }
.no-drop         { cursor: no-drop; }
.not-allowed     { cursor: not-allowed; }
.all-scroll      { cursor: all-scroll; }
.col-resize      { cursor: col-resize; }
.row-resize      { cursor: row-resize; }
.n-resize        { cursor: n-resize; }
.e-resize        { cursor: e-resize; }
.s-resize        { cursor: s-resize; }
.w-resize        { cursor: w-resize; }
.ns-resize       { cursor: ns-resize; }
.ew-resize       { cursor: ew-resize; }
.ne-resize       { cursor: ne-resize; }
.nw-resize       { cursor: nw-resize; }
.se-resize       { cursor: se-resize; }
.sw-resize       { cursor: sw-resize; }
.nesw-resize     { cursor: nesw-resize; }
.nwse-resize     { cursor: nwse-resize; }

// You can also have the cursor be an image:
.custom {
cursor: url(images/my-cursor.png), auto;
}


## display

### none

The value "none" lets you turn off the display of an element; when you use "none", all descendant elements also have their display turned off. The document is rendered as though the element doesn't exist in the document tree.

## grid

### grid-template-columns

#### repeat



#container {
display: grid;
grid-template-columns: repeat(2, 50px 1fr) 100px; /* Columns consist of 5 cols: 50px-width-col, flexible-width-col, 50px-width-col, flexible-width-col, 100px-width-col.
grid-gap: 5px;
box-sizing: border-box;
height: 200px;
width: 100%;
background-color: #8cffa0;
}


## text-align



text-align: justify; // causes all lines of text except the last line to meet the left and right edges of the line box.


### How to center a div

SO.



//---------- text-align center the outer
#outer {
width: 100%;
text-align: center;
}
#inner {
display: inline-block;
}

//---------- display table the inner
// If you can't add text-align to the outer, then you have to make the inner a table:
#inner {
display: table;
margin: 0 auto;
}


## text-decoration

none	Defines a normal text. This is default.
underline 	Defines a line below the text.
overline 	Defines a line above the text.
line-through 	Defines a line through the text.
initial		Sets this property to its default value.
inherit		Inherits this property from its parent element.


## text-overflow



.ellipsis {
text-overflow: ellipsis;

/* Required for text-overflow to do anything */
white-space: nowrap;
overflow: hidden;
}


Note that text-overflow only occurs when the container's overflow property has the value "hidden, scroll or auto" and "white-space: nowrap;".

## border

### border property



<line-width> || <line-style> || <color>
where
<line-width> = <length> | thin | medium | thick
<line-style> = none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset
<color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color>

border: solid;
border: dashed red;
border: 1rem solid;
border: thick double #3212ce;
border: 4mm ridge rgb(170, 150, 225, 0.5);

/* NOTE: There is no:
border: 1px 2px 3px 4px solid black; */


Outlines never take up space, as they are drawn outside of an element's content.

I have a border, an outline, AND a box shadow!



div {
border: 0.5rem solid pink;

box-shadow: 0 0 0 2rem skyblue;

outline: 0.5rem solid khaki;
outline-offset: 0.5rem;

font: bold 1rem sans-serif;
margin: 2rem;
}


### border-collapse

The border-collapse property is for use on "table" or "table-like" elements.

separate (default) - in which all table cells have their own independent borders and there may be space between those cells as well.
collapse - in which both the space and the borders between table cells collapse so there is only one border and no space between cells.


table {
border-collapse: separate; /* Or do nothing, this is default */
border-spacing: 3px; /* Only works if border-collapse is separate */
}


### How to collapse/merge div borders

SO. "border-collapse" is only used in tables. Here is the method for divs:



div {
// Here is how it works: first float, then -1px the margin.
float:left;
margin-left: -1px;
margin-top: -1px;

// This is only for visualisation.
background-color:moccasin;
width:100px;
height:100px;
border:1px solid tomato;
}


### border-width

Note: Always declare the border-style property before the border-width property. An element must have borders before you can set the width.

#### Four values



border-width: thin medium thick 10px;
top border is thin
right border is medium
bottom border is thick
left border is 10px

border-width: thin medium thick;
top border is thin
right and left borders are medium
bottom border is thick

border-width: thin medium;
top and bottom borders are thin
right and left borders are medium

border-width: thin;
all four borders are thin


none 	Default value. No shadow is displayed
h-shadow 	Required. The position of the horizontal shadow. Negative values are allowed
v-shadow 	Required. The position of the vertical shadow. Negative values are allowed
blur 	Optional. The blur distance.
color 	Optional. The color of the shadow. The default value is black.

Note: In Safari (on PC) the color parameter is required. If you do not specify the color, the shadow is not displayed at all.

box-shadow: h-offset v-offset [blur spread color];

box-shadow: 0px 10px 20px rgba(0,0,0,0.19), 0px 6px 6px rgba(0,0,0,0.23);


## box-sizing

The current versions of all browsers use the original "width or height + padding + border = actual width or height" box model. With box-sizing: border-box;, we can change the box model to what was once the "quirky" way (jefftk.com: IE has done the box model right), where an element's specified width and height aren't affected by padding or borders. This has proven so useful in responsive design that it's found its way into reset styles.

Universal reset:


html {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
*, *:before, *:after {
-webkit-box-sizing: inherit;
-moz-box-sizing: inherit;
box-sizing: inherit;
}


## flex related

The main idea behind the flex layout is to give the container the ability to alter its items' width/height (and order) to best fill the available space (mostly to accommodate to all kind of display devices and screen sizes). A flex container expands items to fill available free space, or shrinks them to prevent overflow.

Most importantly, the flexbox layout is direction-agnostic as opposed to the regular layouts (block which is vertically-based and inline which is horizontally-based). While those work well for pages, they lack flexibility (no pun intended) to support large or complex applications (especially when it comes to orientation changing, resizing, stretching, shrinking, etc.).

### Properties for the Parent



.container {
display: flex; /* or inline-flex */

flex-direction: row | row-reverse | column | column-reverse;
flex-wrap: nowrap | wrap | wrap-reverse; /* By default, flex items will all try to fit onto one line. You can change that and allow the items to wrap as needed. */
flex-flow: <‘flex-direction’> || <‘flex-wrap’>; /* a shorthand flex-direction and flex-wrap properties. */

justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly; /* defines the alignment along the main axis. */
align-items: flex-start | flex-end | center | baseline | stretch; /* defines the default behaviour for how flex items are laid out along the cross axis. "center" will align by the center of children; "baseline" will align by the text baseline of children. "stretch" will make children occupy the whole hight. */
align-content: flex-start | flex-end | center | space-between | space-around | stretch; /* This aligns a flex container's lines within when there is more than one lines in the cross-axis. */
}


#### justify-content

It defines the alignment along the main axis.

flex-start (default): items are packed toward the start line
flex-end: items are packed toward to end line
center: items are centered along the line

space-between: items are evenly distributed in the line; first item is on the start line, last item on the end line
space-around: items are evenly distributed in the line with equal space around them
space-evenly: items are distributed so that the spacing between any two adjacent alignment subjects, before the first alignment subject, and after the last alignment subject is the same



<style>
.flex-container {
margin: 0;
list-style: none;
display: flex;
}

.flex-start {
justify-content: flex-start;
}

.flex-item {
background: tomato;
width: 60px;
height: 50px;
margin: 5px;
line-height: 50px;
color: white;
font-weight: bold;
font-size: 2em;
text-align: center;
}
</style>

<ul class="flex-container flex-start">
<li class="flex-item">1</li>
<li class="flex-item">2</li>
<li class="flex-item">3</li>
<li class="flex-item">4</li>
<li class="flex-item">5</li>
</ul>


#### align-content

It helps aligning a flex container's lines within it when there is extra space in the cross-axis (e.g. y-axis), similar to how justify-content aligns individual items within the main-axis (e.g. x-axis).

This property has no effect when the flexbox has only a single line.

stretch (default): lines stretch to take up the remaining space
flex-start: lines packed to the start of the container
flex-end: lines packed to the end of the container
center: lines packed to the center of the container

space-between: lines evenly distributed; the first line is at the start of the container while the last one is at the end
space-around: lines evenly distributed with equal space between them


### Properties for the Children: order, flex-grow



.item {
order: <integer>; /* Default is 0. By default, flex items are laid out in the source order. */
flex-grow: <number>; /* default 0. If all items have flex-grow set to 1, the remaining space in the container will be distributed equally to all children. */
flex-shrink: <number>; /* default 1. This defines the ability for a flex item to shrink if necessary. */
flex-basis: <length> | auto; /* default auto. This defines the default size of an element before the remaining space is distributed. It can be a length (e.g. 20%, 5rem, etc.) or a keyword. */
flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]; /* Shorthand for flex-grow, flex-shrink and flex-basis combined. Default is 0 1 auto. It is recommended that you use this shorthand property rather than set the individual properties. The short hand sets the other values intelligently. */
align-self: auto | flex-start | flex-end | center | baseline | stretch; /* allows the default alignment (or the one specified by align-items) to be overridden for individual flex items. */
}


## margin



// To center something horizontally in modern browsers, you can use
display: flex;
justify-content: center;
box-sizing: border-box;
width: 100%;

// However, in older browsers like IE8-9 that do not support Flexible Box Layout, these are not available. In order to center an element inside its parent, use
margin: 0 auto;
box-sizing: border-box;
width: 100%;


### auto

auto: The browser selects a suitable margin to use. For example, in certain cases this value can be used to center an element.

wcfNote: when a div has "margin: auto", it may have a longer width than its parent. learnLayout.com.

### Margin collapsing

Elements' top and bottom margins are sometimes collapsed into a single margin that is equal to the larger of the two margins.

## outline

It's similar to border except that:

• It always goes around all the sides, you can't specify particular sides
• It's not a part of the box model, so it won't effect the position of the element or adjacent elements

It is often used for accessibility reasons, to emphasize a link when tabbed to without affecting positioning and in a different way than hover.


a:focus {
outline-width: 1px;
outline-style: dashed;
outline-color: red;
}


## overflow, controls the scroll-bar

visible	The overflow is not clipped. It renders outside the element's box. This is default.
hidden	The overflow is clipped, and the rest of the content will be invisible
scroll	The overflow is clipped, but a scroll-bar is added to see the rest of the content
auto	If overflow is clipped, a scroll-bar should be added to see the rest of the content


.box {
overflow-y: hidden;
overflow-x: scroll;
}


### Float Clearing

One of the more popular uses of setting overflow, strangely enough, is float clearing. The element with overflow (any value except visible) will extend (instead of collapsing) as large as it needs to encompass floated child elements inside, assuming that the height isn't declared. css-tricks.com: float clearing.

A better float clearing technique is the clearfix, as it doesn't require you to alter the overflow property in a way you don't need.

#### clearfix

The Clearfix: Force an Element To Self-Clear its Children.


.group:after {
content: "";
display: table;
clear: both;
}



<div class="group">
<div class="is-floated"></div>
<div class="is-floated"></div>
<div class="is-floated"></div>
</div>


You would use this instead of clearing the float with something like <br style="clear: both;" />at the bottom of the parent (easy to forget, not handleable right in CSS, non-semantic) or using something like overflow: hidden; on the parent (you don't always want to hide overflow).

### Generating block formatting context

It’s interesting to note that overflow will also create a new block formatting context which is useful if we want to align a block element next to a floated one. css-tricks.

## transform

The transform property allows you to visually manipulate an element by skewing, rotating, translating, or scaling.

scale(): affects the size of the element. This also applies to the font-size, padding, height, and width of an element, too. It’s also a a shorthand function for the scaleX and scaleY functions.
skewX() and skewY(): tilts an element to the left or right, like turning a triangle into a parallelogram. There is no shorthand skew property.
translate(): moves an element sideways or up and down.
rotate(): rotates the element clockwise from its current position.
matrix(): a function that is probably not intended to be written by hand, but combines all transforms into one.
perspective(): doesn’t affect the element itself, but affects the transforms of descendent elements' 3D transforms, allowing them all to have a consistent depth perspective.



//---------- This makes an animation that translates a box back and forth

.square {
height: 100px;
width: 100px;
background-color: #3d9970;
display: flex;
text-align: center;
justify-content: center;
align-content: center;
color: white;
animation: shimmy 3s infinite;
animation-direction: alternate;
}

@keyframes shimmy {
0% {
transform: translate(0, 0);
}
100% {
transform: translate(20px, 50px);
}
}

//---------- Others

.element {
transform: rotate(25deg);
}


It modifies the coordinate space of the CSS visual formatting model.

## user-select

The user-select property in CSS controls how the text in an element is allowed to be selected. For example, it can be used to make text unselectable, so that the reader can't copy and paste.


user-select: auto / all / none;


## vertical-align

### vertical-align, inline-blocks and line-height

brunildo.org provides a very good example demoing the different effects of inline-blocked "span"s with different "vertical-align".

vertical-align:
top
bottom
baseline
middle
text-top
text-bottom

top and bottom should always touch the box horizontal borders.


## width, min-width, max-width

The width CSS property specifies the width of the content area of an element. The content area is inside the padding, border, and margin of the element.

The max-width property overrides the width property, but min-width will always override max-width. So the precedence: min-width, max-width, width.

[ <length> | <percentage> ] && [ border-box | content-box ]? | available | min-content | max-content | fit-content | auto


## height

### Set the height of a div to 100%

The percentage (%) is a relative unit so the resulting height is depends on the height of parent element's height.

The container div has two parent elements: body and html. We all know the default value of height property is auto, so if we also set both the height of body and html element to 100% the resulting height of container div becomes equal the 100% height of the browser window.



html, body {
height: 100%;
margin: 0px;
}

.container {
height: 100%;
background: #f0e68c;
}


### height: auto

In Bootstrap, height: auto; is used in .img-responsive, so that the image preserve its aspect-ratio when scaling.


.img-responsive {
display: block;
max-width: 100%;
height: auto;
}


## word-break

normal 	Default value. Break words according to their usual rules.
break-all 	Lines may break between any two letters.
keep-all  	Breaks are prohibited between pairs of letters.


Normally, line breaks in text can only occur in certain spaces, like when there is a space or a hyphen.

In the example below we can make the word-break between letters instead:


p {
word-break: break-all;
}


If we then set the width of the text to one em, the text line will become a vertical text line.

This value is often used in places with user generated content so that long strings don't risk breaking the layout. One very common example is a long copy and pasted URL. If that URL has no hyphens, it can extend beyond the parent box and look bad or worse, cause layout problems.

This property is also often used in conjunction with the hyphens property so that when breaks occur a hypen is inserted, as per the standard in books.


// The full usage, with needed vendor prefixes, is:

-ms-word-break: break-all;
word-break: break-all;

/* Non standard for WebKit */
word-break: break-word;

-webkit-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;


### word-break vs word-wrap

word-wrap: break-word: will wrap long words onto the next line, and adjusts different words so that they do not break in the middle. wcfNote: this may be preferred in business value.

word-break: break-all: irrespective of whether it’s a continuous word or many words, breaks them up at the edge of the width limit. (i.e. even within the characters of the same word).

word-wrap: break-word recently changed to overflow-wrap: break-word.

## word-wrap, overflow-wrap

word-wrap: break-word recently changed to overflow-wrap: break-word.

normal 	Break words only at allowed break points
break-word 	Allows unbreakable words to be broken
inherit


#### pre tag not affected by word-wrap:break-word?


pre {
white-space: pre-wrap;		 /* CSS 3 */
white-space: -moz-pre-wrap;	 /* Mozilla, since 1999 */
white-space: -pre-wrap;		 /* Opera 4-6 */
white-space: -o-pre-wrap;	 /* Opera 7 */
word-wrap: break-word;		 /* Internet Explorer 5.5+ */
}


To be more browser robust, use the following: Reference


word-wrap:break-word;
-ms-word-break: break-all;
/* Be VERY careful with this, breaks normal words wh_erever */
word-break: break-all;
/* Non standard for webkit */
word-break: break-word;
-webkit-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;


## white-space

normal 	Sequences of whitespace will collapse into a single whitespace. Text will wrap when necessary. This is default.
nowrap 	Sequences of whitespace will collapse into a single whitespace. Text will never wrap to the next line.
pre 	Whitespace is preserved by the browser. Text will only wrap on line breaks. Acts like the pre tag in HTML.
pre-line 	Sequences of whitespace will collapse into a single whitespace. Text will wrap when necessary, and on line breaks.
pre-wrap 	Whitespace is preserved by the browser. Text will wrap when necessary, and on line breaks .


## hyphens

none	Words are never hyphenated at at line breaks.
manual	Words are only broken at line breaks where there are characters inside the word that suggest line break opportunities.
auto	Words can be broken at appropriate hyphenation points either as determined by hyphenation chars or as determined automatically by a language-appropriate hyphenation resource (if supported by the browser or provided via @hyphenation-resource).

The hyphenation chars for manual breaks are
• U+2010 "-"
• U+00AD &shy; This character is not rendered visibly; instead, it suggests a place where the browser might choose to break the word if necessary.

## Positions: relative, fixed, absolute

Block-level items automatically start on a new line (think headings, paragraphs, and divs) while inline items sit within surrounding content (like images or spans). The default layout of elements in this way is called the normal flow of a document, but CSS offers the position property to override it.

When the position of an element is set to relative, it allows you to specify how CSS should move it relative to its current position in the normal flow of the page. It pairs with the CSS offset properties of left or right, and top or bottom.

static. The default. Any element with static position is said to be not positioned, otherwise is said to be positioned.

relative. The element is adjusted away from its normal position by setting top, right, bottom, left properties. See example below.
Other contents will not take its place, e.g. a relative element holds its place. This makes "relative" appear not very useful, but it performs an important task: setting ancestral container for "absolute" element. See example below.

fixed. The element is positioned relative to the viewport. It does not leave a gap, in other words, its element will not occupy a position in normal flow.

absolute. Behaves like fixed but relative to the nearest positioned ancestor. Remember, "absolute" is to "relative", but not "fixed".


Relative example:


#div-1 {
position:relative;
top:20px;
left:-40px;
}


If we set relative positioning on div-1, any elements within div-1 will be positioned relative to div-1. Then if we set absolute positioning on div-1a, we can move it to the top right of div-1.


#div-1 {
position:relative;
}
#div-1a {
position:absolute;
top:0;
right:0;
width:200px;
}


/* If we float one column to the left, then also float the second column to the left, they will push up against each other. */
#div-1a {
float:left;
width:190px;
}
#div-1b {
float:left;
width:190px;
}

/* Then after the floating elements we can "clear" the floats to push down the rest of the content. */
#div-1c {
clear:both;
}


## float and clear

Float is used to wrapping text around images, such as


img {
float: right;
margin: 0 0 1em 1em;
}


will put images on the right of its container, and the image has a margin with regards to surrounding text.

Sometimes when floated elements cause trouble to its followers, its followers could use clear to get rid of it. For example, the element following a left-floated div could use clear: left.

# Grammer

## Selectors

### Grouping Selectors


h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}

/* Is the same as: */
h1, h2 {
text-align: center;
color: red;
}


### Descendant selector

Ref.

h1 em {color:red;}
• 选择器之间的空格是一种结合符（combinator）.
• 两个元素之间的层次间隔可以是无限的。例如"ul em"，这个语法就会选择从 ul 元素继承的所有 em 元素，而不论 em 的嵌套层次多深。


// Use a white space to match all descendants of an element:
div.dropdown * {
color: red;
}


### Child selector

#### Child and sibling selectors



/* Decendent selector */
table td { }

/* Child selector.

h1 > strong {color:red;}

p + p { font-size: smaller; } /* Selects all paragraphs that follow another paragraph */

/* General sibling combinator */
/* Very similar to the adjacent sibling selector. The difference is that that the element being selected doesn't need to immediately succeed the first element, but can appear anywhere after it.
p ~ p { }

/* Not yet supported! */
p < img { width: 150%; } /* select all paragraphs that contain images */
/* Apparently the powers that be have rejected it a number of times for some complicated reasons (speed related, I think). jQuery can do it: */
$("p:has(img)") /* ---------- More examples */ /* 选择作为 td 元素子元素的所有 p 元素，这个 td 元素本身从 table 元素继承，该 table 元素有一个包含 company 的 class 属性。*/ table.company td > p // Use a white space to match all children of an element: div.dropdown > * { color: red; }  #### Q: is there any parent selectors? There is currently no way to select the parent of an element in CSS. You'll have to resort to JavaScript if you need to select a parent element. $( "div:has(p)" ).addClass( "test" );

The Selectors Level 4 Working Draft includes a :has() pseudo-class that works the same as the jQuery implementation. As of 2018, this is still not supported by any browser.

Using :has() the original question could be solved with this:


li:has(> a.active) { /* styles to apply to the li tag */ }

#### jQuery

Format: jQuery( ":has(selector)" )

For example, the expression $( "div:has(p)" ) matches a "div" if a "p" exists anywhere among its descendants, not just as a direct child. $( "div:has(p)" ).addClass( "test" );

#### CSS4 WD (not supported yet)

The Selectors Level 4 Working Draft includes a :has() pseudo-class that works the same as the jQuery implementation.


<!-- Select the <li> element that is a immediate parent of the anchor tag -->
li:has(> a.active) { /* styles to apply to the li tag */ }


/* 例如，如果要增加紧接在 h1 元素后出现的段落的上边距，可以这样写：*/
h1 + p {margin-top:50px;}


### General sibling selectors

Selects nodes that follow (not necessarily immediately) the former specified element, if both elements shared the same parent.


/* match all <span> elements that follow a <p> element inside the same element. */
p ~ span {}

### Attribute selectors

Introduced in CSS2. Ref.

[attribute] 	选取带有指定属性的元素。
[attribute=value] 	The attribute has to have the exact value specified.
[attribute~=value] 	The attribute's value needs to be a whitespace separated list of words (for example, class="title featured home"), and one of the words is exactly the specified value.
[attribute|=value] 	The attribute's value is exactly "value" or starts with the word "value" and is immediately followed by "-", so it would be "value-".
[attribute^=value] 	The attribute's value starts with the specified value.
[attribute$=value] The attribute's value ends with the specified value. [attribute*=value] The attribute's value contains the specified value.   /* 包含标题（title）的所有元素变为红色：*/ *[title] {color:red;} /* 只对有 href 属性的锚（a 元素）应用样式： */ a[href] {color:red;} /* 将同时有 href 和 title 属性的 HTML 超链接的文本设置为红色：*/ a[href][title] {color:red;} /* 所有带有 alt 属性的图像应用样式，突出显示这些有效的图像。更适合用来诊断而不是设计。*/ img[alt] {border: 5px solid red;} /* 将指向 Web 服务器上某个指定文档的超链接变成红色：*/ a[href="http://www.w3school.com.cn/about_us.asp"] {color: red;} /* 选择 class 属性中包含 important 的元素。如果忽略了波浪号，则说明需要完成完全值匹配。*/ p[class~="important"] {color: red;} /* 可以匹配如下 */ <p class="important warning">This paragraph is a very important warning. /* all the div elements that are posts */ div[class*="post"] { background-color: #333; } a[href$=".jpg"] {
background: url(jpeg.gif) no-repeat left 50%;
a[href=".pdf"] { background: url(pdf.gif) no-repeat left 50%; padding: 2px 0 2px 20px; } ### CSS precedence we sometimes have the tendency to litter our HTML with excessive and unnecessary classes and ids, divs and spans. The best way is using more complex CSS selectors, ones that can target specific elements without the need of a class or an id. 1. Author > User > default. 2. !important > normal. 3. Specificity. Calculate as (a,b,c,d). See below for example. 1. Inline style 2. ID 3. class, pseudo class, attribute selectors (li[id=red]). 4. element, pseudo element 4. Latter > earlier. A good reference. #### override with !important  td {height: 100px !important}  ### Calculate specificity  p: 1 element - (0,0,0,1) div: 1 element - (0,0,0,1) #sidebar: 1 id - (0,1,0,0) div#sidebar: 1 element, 1 id - (0,1,0,1) div#sidebar p: 2 elements, 1 id - (0,1,0,2) div#sidebar p.bio: 2 elements, 1 class, 1 id - (0,1,1,2) div p.bio {font-size: 14px} - (0,0,1,2) #sidebar p {font-size: 12px} - (0,1,0,1)  # FAQ ## Comment A CSS comment is deliminated by /* and */. The comment can span multiple lines. ## Center "margin: auto;" only works if you have a valid DOCTYPE declaration on top of your page. See this like for why doctype is so important. This will work in every browser except for IE5/Windows. If you want it to work there, you have to wrap another "div" around #content and give it the CSS property of "text-align: center;".  #content { width: 600px; margin-left: auto; margin-right: auto; }  ### Set width and centered  html { margin: 0 auto; max-width: 900px; } body { /* whatever you want */ }  ## HTML and its fonts #### Font names There are two types of font family names: • family-name. Examples: times, courier, etc. • generic-family. Examples: serif, sans-serif, monospace, fantasy, cursive. When setting font-family, always start with the font you want, and end with a generic family name so that the browser could fall back on it. Example:  body { font-family: courier, sans-serif, monospace; }  #### TT, teletype, monospace Reference. The TT tag specifies that the enclosed text must be rendered in a teletype/monospaced font. The tag is not supported in HTML5, so use CODE etc instead. Other similar tags include: • CODE. By default use monospaced font. Multiple spaces are collapsed. • VAR. Variables. Usually rendered in monospace. Multiple spaces are collapsed. • SAMP. Sample text. By default use normal font. • KBD. Keyboard input. By default use normal font. • PRE. By default monospaced. #### EM, emphasized text, italics Although usually EM has the same effect as I, the two must be used non-interchageably: I specifies directly the italic font, while EM indicates that its enclosed text must be emphasized. EM must be rendered differently from STRONG (strongly emphasized text, usually rendered in bold). Other similar tags include: • CITE. Usually rendered in italics. • BLOCKQUOTE. Multi-line citations. It is often rendered with indented margins and possibly in italics, although for E-mail, a symbol '<' may be used instead. • DFN. Definition of a term. Usually in italics. • ADDRESS. Usually used to enclose contact information. Often rendered with an indentation and in italics. #### white-space The CSS white-space could be: • normal. The long lines wrap, spaces are collapsed, and returns are omitted. • nowrap. The long lines don't wrap, spaces are collapsed. • pre. Behaves like the pre tag: long lines don't wrap, spaces are kept, and returns are kept. • pre-wrap. The long lines wrap, spaces are kept, and returns are kept. • pre-line. The long lines wrap, spaces are collapsed, and returns are kept. It is similar to the normal, except for keeping the returns. The CSS-trics page explains well the relationships of pre, pre-wrap and pre-line, and it gives an excellent summary table. This page give a good example. ### Box model #### The width As defined in box model, the width of an element is just the width of its content. When designing a layout, its padding and border width may cause the mis-alignment. For such an element as follows, its box has a visual width of 210px:  p#big { width: 100px; border: 10px; padding: 100px; }  In order to add the counting of padding and border width into the box width, we can set the following:  * { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; }  Then when we set an element with width equal to 200px, its total box width is 200px. Go to learlayout.com for reference. #### calc in css3 In CSS3 there comes a powerful tool: calc. It supports these operators: "+ - * /". Example: width: calc(100% - 2px*2); Note that the two operators "+ -" must be surrounded by spaces, so this is wrong: width: calc(100%-2px*2); #### transition An example. When you hover the mouse on the div element, the transition takes effect.  div { width:100px; height:100px; background:red; transition:width 2s; -moz-transition:width 2s; /* Firefox 4 */ -webkit-transition:width 2s; /* Safari and Chrome */ -o-transition:width 2s; /* Opera */ } div:hover { width:300px; }  #### z-index All elements has a default z-index of 0. The element with lower z-index is beneath those with higher z-index. wcfNote: imagine z-index as a z-axis, pointing upwards to the readers. Note: z-index only works on positioned elements (position:absolute, position:relative, or position:fixed). # Pseudo classes/elements Pseudo class has the format: "element:pClassName". Pseudo element has the format: "element::pElementName". Selector Example Example description :link a:link Selects all unvisited links :visited a:visited Selects all visited links :active a:active Selects the active link :hover a:hover Selects links on mouse over :focus input:focus Selects the input element which has focus ::first-letter p::first-letter Selects the first letter of every <p> element ::first-line p::first-line Selects the first line of every <p> element :first-child p:first-child Selects every <p> elements that is the first child of its parent ::before p::before Insert content before every <p> element ::after p::after Insert content after every <p> element :lang(language) p:lang(it) Selects every <p> element with a lang attribute value starting with "it" ## Use :before/:after on an input field :after and :before are not supported in Internet Explorer 7 and under, on any elements. It's also not meant to be used on replaced elements such as form elements (inputs) and image elements. In other words it's impossible with pure CSS. However if using jquery you can use (".mystyle").after("add your smiley here");
:after and :before pseudo elements, they can only be put on container elements. Why? Because they are appended inside that particular element. "input" is not a container. "button" for instance is hence you can put them on. Specification actually says: before and after an element's document tree content It explicitly says CONTENT. So an element must be a container.