email Feedback About This Page
This is my summary of w3schools' CSS - The Basics in a one page/file format - using only HTML5/CSS3. It can be used as a quick reference. Quick? There are many details in CSS. Concentrate on a few CSS styles to create your own small library.
CSS is a language that describes the style of an HTML document.
CSS describes how HTML elements should be displayed.
CSS stands for Cascading Style Sheets:
Why?
CSS is used to define styles for your web pages, including the design, layout and variations in display for different devices and screen sizes.
Solved a Big Problem
HTML was NEVER intended to contain tags for formatting a web page!
HTML was created to describe the content of a web page, like:
When tags like <font>, and color attributes were added to the HTML 3.2 specification, it started a nightmare for web developers. Development of large websites, where fonts and color information were added to every single page, became a long and expensive process.
To solve this problem, the World Wide Web Consortium (W3C) created CSS.
CSS removed the style formatting from the HTML page!
The style definitions are normally saved in external .css files.
With an external stylesheet file, you can change the look of an entire website by changing just one file!
A CSS rule-set consists of a selector and a declaration block.
The selector points to the HTML element you want to style.
The declaration block contains one or more declarations separated by semicolons.
Each declaration includes a CSS property name and a value, separated by a colon.
Multiple CSS declarations are separated with semicolons, and declaration blocks are surrounded by curly braces.
We can divide CSS selectors into five categories: | |
---|---|
1. Simple | select elements based on name, id, class, all or group |
2. Combinator | select elements based on a specific relationship between them |
3. Pseudo-class | select elements based on a certain state |
4. Pseudo-elements | select and style a part of an element |
5. Attribute | select elements based on an attribute or attribute value |
The element selector selects HTML elements based on the element name.
The id selector uses the id attribute of an HTML element to select a specific element.
The id of an element is unique within a page, so the id selector is used to select one unique element!
To select an element with a specific id, write a hash (#) character, followed by the id of the element.
The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the class name.
You can also specify that only specific HTML elements should be affected by a class.
p.center { text-align:center; color:red; }
HTML elements can also refer to more than one class. <p class="center large">This paragraph refers to two classes.</p>
📝 Note: A class name cannot start with a number!
The universal selector (*) selects all HTML elements on the page.
The grouping selector selects all the HTML elements with the same style definitions.
Look at the following CSS code (the h1, h2, and p elements have the same style definitions):
from this:
h1 { text-align:center; color:red; } h2 { text-align:center; color:red; } p { text-align:center; color:red; }
h1, h2, p { text-align:center; color:red; }
In group selectors, separate each selector with a comma.
There are three ways of using styles: | |
---|---|
External |
▶ CSS look of an entire website set by one file ▶ use <link> element, in <head></head> section ▶ has.css extension |
Internal | CSS defined inside the <style></style> element, inside the <head></head> section |
Inline | CSS style attribute to desired element - can contain any CSS property |
📝 Note:Do not add a space between the property value and the unit ie. margin-left:20px;. No mention is made about spacing between selector and left curly bracket.
📎 Tip:An inline style loses many of the advantages of a style sheet (by mixing content with presentation). Use this method sparingly.
If some properties have been defined for the same selector (element) in different style sheets, the value from the last read style sheet will be used.
What style will be used when there is more than one style specified for an HTML element?
All the styles in a page will cascade into a new virtual style sheet by the following rules, where number one has the highest priority:
Comments are used to explain the code, and may help when you edit the source code at a later date.
Comments are ignored by browsers.
A CSS comment starts with /* and ends with */
Comments can added anywhere in the code.
Comments can span multiple lines.
📚 🎓 Advanced There are 140 standard color names.
Background ▶ background-color property
Text ▶ color property
Border ▶ border property
→ ie. border:2px solid DodgerBlue;
Colors can be specified using: | ||
---|---|---|
color names | ||
RGB | rgb(red, green, blue) | Each parameter defines the intensity of the color between 0 and 255 |
RGBA | rgba(red, green, blue, alpha) | extension of RGB color values with an alpha channel - which specifies the opacity for a color. alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at all) |
HEX | #rrggbb | rr (red), gg (green) and bb (blue) are hexadecimal values between 00 and ff (decimal 0-255) |
HSL | hsl(hue, saturation, lightness) |
Hue = a degree on the color wheel from 0 to 360. 0 is red, 120 is green, and 240 is blue Saturation = a percentage value, 0% means a shade of gray, and 100% is the full color Lightness = a percentage, 0% is black, 50% is neither light or dark, 100% is white |
HSLA | hsla(hue, saturation, lightness, alpha) | extension of HSL color values with an alpha channel - which specifies the opacity for a color alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at all) |
background-color specifies the background color of an element
background-image specifies an image to use as the background of an element -by default, the image is repeated so it covers the entire element.
background-repeat By default, the background-image property repeats an image both horizontally and vertically
background-repeat:no-repeat Shows background image only once
background-position property is used to specify the position of the background image.
body { background-image:url("img_tree.png"); background-repeat:no-repeat; background-position:right top; }
background-attachment specifies whether the background image should scroll or be fixed (will not scroll with the rest of the page):
body { background-image:url("img_tree.png"); background-repeat:no-repeat; background-position:right top; background-attachment:fixed; }
background is shorthand to specify all the background properties in one single property:
from:
body { background-color:#ffffff; background-image:url("img_tree.png"); background-repeat:no-repeat; background-position:right top; }
body { background:#ffffff url("img_tree.png") no-repeat right top; }
When using the background property the order of the property values is:
All CSS Background Properties: | |
---|---|
Property | Description |
background | Sets all the background properties in one declaration |
background-attachment | Sets whether a background image is fixed or scrolls with the rest of the page |
background-clip | Specifies the painting area of the background |
background-color | Sets the background color of an element |
background-image | Sets the background image for an element |
background-origin | Specifies where the background image(s) is/are positioned |
background-position | Sets the starting position of a background image |
background-repeat | Sets how a background image will be repeated |
background-size | Specifies the size of the background image(s) |
The opacity property specifies the opacity/transparency of an element.
div { background-color:green; opacity:0.3; }
If you do not want to apply opacity to child elements, use RGBA color values. ie. set opacity for background color- not the text.
border properties specify an element's border:
The border-style property specifies what kind of border to display.
The following values are allowed: | |
---|---|
dotted | Defines a dotted border |
dashed | Defines a dashed border |
solid | Defines a solid border |
double | Defines a double border |
groove | Defines a 3D grooved border. The effect depends on the border-color value |
ridge | Defines a 3D ridged border. The effect depends on the border-color value |
inset | Defines a 3D inset border. The effect depends on the border-color value |
outset | Defines a 3D outset border. The effect depends on the border-color value |
none | Defines no border |
hidden | Defines a hidden border |
p.dotted { border-style:dotted; }
border-style property can have from one to four values - for:
📝 Note:None of the OTHER CSS border properties will have ANY effect unless the border-style property is set!
border-width property specifies the width of the four borders
The width can be set as a specific size:
p.one { border-style:solid; border-width:5px; }
The border-width property can have from one to four values:
p.one { border-style:solid; border-width:5px 20px; /* 5px top and bottom, 20px on the sides */ } p.two { border-style:solid; border-width:20px 5px; /* 20px top and bottom, 5px on the sides */ } p.three { border-style:solid; border-width:25px 10px 4px 35px; /* 25px top, 10px right, 4px bottom and 35px left */ }
The border-color property is used to set the color of the four borders.
The color can be set by: | |
---|---|
name | specify a color name, like red |
HEX | specify a HEX value, like #ff0000 |
RGB | specify a RGB value, like rgb(255,0,0) |
HSL | specify a HSL value, like hsl(0, 100%, 50%) |
transparent |
📝 Note: If border-color is not set, it inherits the color of the element.
p.one { border-style:solid; border-color:red; }
The border-color property can have from one to four values:
p.one { border-style:solid; border-color:red green blue yellow; /* red top, green right, blue bottom and yellow left */ }
border color can be specified using: | |
---|---|
names | border-color:red green blue yellow; /*top right bottom left */ |
hex | border-color:#ff0000; /* red */ |
rgb | border-color:rgb(255, 0, 0); /* red */ |
hsl | border-color:hsl(0, 100%, 50%); /* red */ |
Individual Sides
▶ it is possible to specify a different border for each side.
There are properties for specifying each of the borders:
p { border-top-style:dotted; border-right-style:solid; border-bottom-style:dotted; border-left-style:solid; }
p { border-style: dotted solid; }
If the border-style property has four values:
If the border-style property has three values:
If the border-style property has two values:
If the border-style property has one value:
The border-style property also works with border-width and border-color.
To shorten the code, it is possible to specify all the individual border properties in one property: border
border property is shorthand for the following individual border properties:
p { border:5px solid red; }
p { border-left:6px solid red; background-color:lightgrey; }
border-radius property is used to add rounded borders to an element
p { border:2px solid red; border-radius:5px; }
All CSS Border Properties | |
---|---|
Property | Description |
border | Sets all the border properties in one declaration |
border-bottom | Sets all the bottom border properties in one declaration |
border-bottom-color | Sets the color of the bottom border |
border-bottom-style | Sets the style of the bottom border |
border-bottom-width | Sets the width of the bottom border |
border-color | Sets the color of the four borders |
border-left | Sets all the left border properties in one declaration |
border-left-color | Sets the color of the left border |
border-left-style | Sets the style of the left border |
border-left-width | Sets the width of the left border |
border-radius | Sets all the four border-*-radius properties for rounded corners |
border-right | Sets all the right border properties in one declaration |
border-right-color | Sets the color of the right border |
border-right-style | Sets the style of the right border |
border-right-width | Sets the width of the right border |
border-style | Sets the style of the four borders |
border-top | Sets all the top border properties in one declaration |
border-top-color | Sets the color of the top border |
border-top-style | Sets the style of the top border |
border-top-width | Sets the width of the top border |
border-width | Sets the width of the four borders |
Margin properties are used to create space around elements, outside of any defined borders.
Can have full control over the margins.
There are properties for setting the margin for each side of an element:
CSS has properties for specifying the margin for each side of an element:
All the margin properties can have the following values: | |
---|---|
auto | the browser calculates the margin |
length | specifies a margin in px, pt, cm, etc. - to get 0 top try: margin-top:-1.0em; |
% | specifies a margin in % of the width of the containing element |
inherit | specifies that the margin should be inherited from the parent element |
📎 Tip: Negative values are allowed.
p { /*margin-top:-1.0em; to get 0 top try: margin-top:-1.0em;*/ margin-top:100px; margin-bottom:100px; margin-right:150px; margin-left:80px; }
margin property is shorthand for all the margin properties.
margin property is shorthand for the following individual margin properties:
If the margin property has four values:
If the margin property has three values:
If the margin property has two values:
If the margin property has one value:
Setting margin property to auto will horizontally center the element within its container.
The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.
div { width:300px; margin:auto; border:1px solid red; }
div { border:1px solid red; margin-left:100px; } p.ex1 { margin-left:inherit; }
Top and bottom margins of elements are sometimes collapsed into a single margin that is equal to the largest of the two margins.
This does not happen on left and right margins! Only top and bottom margins!
All CSS Margin Properties | |
---|---|
Property | Description |
margin | shorthand to set margin properties in one declaration |
margin-bottom | sets bottom margin of an element |
margin-left | sets left margin of an element |
margin-right | sets right margin of an element |
margin-top | sets top margin of an element |
Used to generate space around an element's content, inside of any defined borders.
You have full control over padding.
There are properties for setting the padding for each side of an element:
Properties for specifying the padding for each side of an element:
All the padding properties can have the following values: | |
---|---|
length | specifies a padding in px, pt, cm, etc. |
% | specifies a padding in % of the width of the containing element |
inherit | specifies that the padding should be inherited from the parent element |
📝 Note: Negative values are not allowed.
div { padding-top:50px; padding-right:30px; padding-bottom:50px; padding-left:80px; }
padding property is shorthand for the following individual padding properties:
If the padding property has four values:
If the padding property has three values:
If the padding property has two values:
If the padding property has one value:
The CSS width property specifies the width of the element's content area. The content area is the portion inside the padding, border, and margin of an element (the box model).
If an element has a specified width, the padding added to that element will be added to the total width of the element. This is often an undesirable result.
Can use the box-sizing property. This causes the element to maintain its width; if you increase the padding, the available content space will decrease.
div { width:300px; padding:25px; box-sizing:border-box; }
All CSS Padding Properties | |
---|---|
Property | Description |
padding | shorthand property for setting all padding properties in one declaration |
padding-bottom | sets bottom padding of an element |
padding-left | sets left padding of an element |
padding-right | sets right padding of an element |
padding-top | sets top padding of an element |
The height and width properties are used to set the height and width of an element.
The height and width properties do not include padding, borders, or margins. It sets the height/width of the area inside the padding, border, and margin of the element.
may have the following values: | |
---|---|
auto | default - browser calculates the height and width |
length | defines height/width in px, cm etc. |
% | defines height/width in percent of containing block |
initial | sets height/width to its default value |
inherit | the height/width will be inherited from its parent value |
The max-width property is used to set the maximum width of an element.
The max-width can be specified in:
A commom problem with a <div> occurs when the browser window is smaller than the width of the element (ie. 500px). The browser will add a horizontal scrollbar to the page.
Using max-width instead, in this situation, will improve the browser's handling of small windows.
All CSS Dimension Properties | |
---|---|
Property | Description |
height | sets height of an element |
max-height | sets maximum height of an element |
max-width | sets maximum width of an element |
min-height | sets minimum height of an element |
min-width | sets minimum width of an element |
width | sets width of an element |
All HTML elements can be considered as boxes. In CSS, the term box model is used when talking about design and layout.
The CSS box model is essentially a box that wraps around every HTML element.
It consists of:
The image below illustrates the box model:
Explanation of the different parts: | |
---|---|
Content | content of the box, where text and images appear |
Padding | Clears an area around the content - padding is transparent |
Border | a border that goes around the padding and content |
Margin | clears an area outside the border - the margin is transparent |
The box model allows adding a border around elements, and to define space between elements.
Need to know how the box model works to set width and height of an element correctly in all browsers,
Important: When you set the width and height properties of an element with CSS, you just set the width and height of the content area. To calculate the full size of an element, you must also add padding, borders and margins.
example:div { width:320px; padding:10px; border:5px solid gray; margin:0; }
Here is the calculation:
total width of an element calculated:
Total element width = width + left padding + right padding + left border + right border + left margin + right margin
total height of an element calculated:
Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin
An outline is a line that is drawn around elements, OUTSIDE the borders, to make the element stand out.
CSS has the following outline properties:
📝 Note: Outline differs from borders! Unlike border, the outline is drawn outside the element's border, and may overlap other content. Also, the outline is NOT a part of the element's dimensions; the element's total width and height is not affected by the width of the outline.
The outline-style property specifies the style of the outline, and can have one of the following values:
p.dotted{ outline-style:dotted; }
The outline-width property specifies the width of the outline, and can have one of the following values:
The outline-color property is used to set the color of the outline.
The color can be set by: | |
---|---|
name | specify a color name, like red |
HEX | specify a hex value, like #ff0000 |
RGB | specify a RGB value, like rgb(255,0,0) |
HSL | specify a HSL value, like hsl(0, 100%, 50%) |
invert | performs a color inversion - which ensures that the outline is visible, regardless of color background |
outline-color:red; outline-color:#ff0000; /* red */ outline-color:rgb(255, 0, 0); /* red */ outline-color:hsl(0, 100%, 50%); /* red */ outline-color:invert;
outline property is shorthand for setting the following individual outline properties:
The outline property is specified as one, two, or three values from the list above. The order of the values does not matter.
p.ex1 {outline:dashed;} p.ex2 {outline:dotted red;} p.ex3 {outline:5px solid yellow;} p.ex4 {outline:thick ridge pink;}
The outline-offset property adds space between an outline and the edge/border of an element. The space between an element and its outline is transparent.
Property | Description |
---|---|
outline | shorthand to set outline-width, outline-style, and outline-color in one declaration |
outline-color | sets color of an outline |
outline-offset | specifies the space between an outline and the edge or border of an element |
outline-style | sets style of an outline |
outline-width | sets width of an outline |
CSS Text
The color property is used to set the color of the text. The color is specified by:
📚 w3schools CSS Legal Color Values
The default text color for a page is defined in the body selector.body { color:blue; }
body { background-color:lightgrey; color:blue; }
The text-align property is used to set the horizontal alignment of a text.
A text can be:
h1 { text-align:center; } h2 { text-align:left; } h3 { text-align:right; }
When text-align:justify; , each line is stretched so that every line has equal width, and the left and right margins are straight (like in magazines and newspapers).
p { direction:rtl; unicode-bidi:bidi-override; }
img.top { vertical-align:top; } img.middle { vertical-align:middle; } img.bottom { vertical-align:bottom; }
The text-decoration property is used to set or remove decorations from text.
text-decoration:none; often used to remove underlines from links
a { text-decoration:none; }
other text-decoration values:
text-transform property specifies uppercase and lowercase letters in text
can be used to turn everything into uppercase or lowercase letters, or capitalize the first letter of each word:
text-indent property is used to specify the indentation of the first line of a text:
h1 { letter-spacing:3px; } h2 { letter-spacing:-3px; }
p.small { line-height:0.8; } p.big { line-height:1.8; }
h1 { word-spacing:10px; } h2 { word-spacing:-5px; }
p { white-space:nowrap; /*disable text wrapping inside an element*/ }
text-shadow property adds shadow text
In its simplest use, only specify the horizontal shadow (2px) and the vertical shadow (2px):h1 { text-shadow:2px 2px; } h1 { text-shadow:2px 2px red; /*add color red*/ } h1 { text-shadow:2px 2px 5px red; /*add blur effect 5px*/ }
All CSS Text Properties | |
---|---|
Property | Description |
color | sets color of text |
direction | specifies text direction/writing direction |
letter-spacing | increases or decreases space between characters in a text |
line-height | sets line height |
text-align | specifies horizontal alignment of text |
text-decoration | specifies decoration added to text |
text-indent | specifies indentation of the first line in a text-block |
text-shadow | specifies shadow effect added to text |
text-transform | controls capitalization of text |
text-overflow | specifies how overflowed content that is not displayed should be signaled to the user |
unicode-bidi | used together with direction property to set or return whether the text should be overridden to support multiple languages in the same document |
vertical-align | sets vertical alignment of an element |
white-space | specifies how white-space inside an element is handled |
word-spacing | increases or decreases space between words in a text |
The CSS font properties define the following for text:
In CSS, there are two types of font family names:
📝 Note: On computer screens, sans-serif fonts are considered easier to read than serif fonts.
The font family of text is set with the font-family property.
The font-family property should hold several font names as a fallback system. If the browser does not support the first font, it tries the next font, and so on.
Start with the font you want, and end with a generic family, to let the browser pick a similar font in the generic family, if no other fonts are available.
📝 Note: If the name of a font family is more than one word, it must be in quotation marks, like: "Times New Roman".
More than one font family is specified in a comma-separated list:.serif { font-family:"Times New Roman", Times, serif; }
🚴 w3schools Web Safe Font Combinations
font-style property has three values:
p.normal { font-style:normal; } p.italic { font-style:italic; } p.oblique { font-style:oblique; }
p.normal { font-weight:normal; } p.thick { font-weight:bold; }
font-variant property specifies whether or not text should be displayed in a small-caps font
In a small-caps font, all lowercase letters are converted to uppercase letters. However, the converted uppercase letters appears in a smaller font size than the original uppercase letters in the text.
p.normal { font-variant:normal; } p.small { font-variant:small-caps; }
font-size property sets text size
Being able to manage text size is important in web design. However, do not use font size adjustments to make paragraphs look like headings, or headings look like paragraphs.
Always use the proper HTML tags, like <h1> - <h6> for headings and <p> for paragraphs.
The font-size value can be:
Absolute size:
Relative size:
📝 Note: If font size is not specified, the default size for normal text, like paragraphs, is 16px (16px=1em).
Setting text size with pixels gives you full control over the text size:
h1 { font-size:40px; }
Many developers use em instead of pixels to allow users to resize the text in the browser menu.
The em size unit is recommended by the W3C.
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
h1 { font-size:2.5em; /* 40px/16=2.5em */ }
The solution that works in all browsers, is to set a default font-size in percent for the <body> element:
body { font-size:100%; } h1 { font-size:2.5em; }
Text size can be set with a vw unit, which means the viewport width.
That way the text size will follow the size of the browser window:
Viewport is the browser window size. 1vw = 1% of viewport width. If the viewport is 50cm wide, 1vw is 0.5cm.
The font property is shorthand for:
p.a { font:20px Arial, sans-serif; } p.b { font:italic small-caps bold 12px/30px Georgia, serif; }
📝 Note: The font-size and font-family values are required. If one of the other values is missing, their default value are used.
All CSS Font Properties | |
---|---|
Property | Description |
font | sets all font properties in one declaration |
font-family | specifies font family for text |
font-size | specifies font size of text |
font-style | specifies font style for text |
font-variant | specifies whether or not text should be displayed in a small-caps font |
font-weight | specifies weight of a font |
The simplest way to add an icon to your HTML page, is with an icon library, such as Font Awesome.
Add the name of the specified icon class to any inline HTML element (like <i> or <span>).
All the icons in the icon libraries below, are scalable vectors that can be customized with CSS (size, color, shadow, etc.).
To use the Font Awesome icons, go to 📚 🎓 Font Awesome Icons, sign in, and get a code to add in the <head> section of your HTML page:
Read more about how to get started with Font Awesome at 📚 🎓 w3schools Font Awesome 5 tutorial.
📝 Note: No downloading or installation is required!
example:<!DOCTYPE html> <html> <head> <script src="https://kit.fontawesome.com/a076d05399.js"></script> </head> <body> <i class="fas fa-cloud"></i> <i class="fas fa-heart"></i> <i class="fas fa-car"></i> <i class="fas fa-file"></i> <i class="fas fa-bars"></i> </body> </html>
For a complete reference of all Font Awesome icons, visit 📚 w3schools Font Awesome Icon Reference.
To use the Bootstrap glyphicons, add the following line inside the <head> section of your HTML page:
📝 Note: No downloading or installation is required!
Example:<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> </head> <body> <i class="glyphicon glyphicon-cloud"></i> <i class="glyphicon glyphicon-remove"></i> <i class="glyphicon glyphicon-user"></i> <i class="glyphicon glyphicon-envelope"></i> <i class="glyphicon glyphicon-thumbs-up"></i> </body> </html>
To use the Google icons, add the following line inside the <head> section of your HTML page:
📝 Note: No downloading or installation is required!
Example:<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> </head> <body> <i class="material-icons">cloud</i> <i class="material-icons">favorite</i> <i class="material-icons">attachment</i> <i class="material-icons">computer</i> <i class="material-icons">traffic</i>
For a complete list of all icons, visit
📚 w3schools Icons Tutorial.
(Only adds a little more info than what's above.)
Links can be styled in different ways.
Links can be styled with any CSS property.
Links can be styled differently depending on what state they are in.
The four links states are:
When setting the style for several link states, there are some order rules:
a:link { text-decoration:none; }
a:link { background-color:yellow; }
a:link, a:visited { background-color:#f44336; color:white; padding:14px 25px; text-align:center; text-decoration:none; display:inline-block; }
In HTML, there are two main types of lists:
The CSS list properties allow you to:
ul.a { list-style-type:circle; /*unordered list*/ } ol.c { list-style-type:upper-roman; /*ordered list*/ }
ul { list-style-image:url('sqpurple.gif'); }
The list-style-position property specifies the position of the list-item markers (bullet points).
list-style-position:outside; means bullet points will be outside the list item. The start of each line of a list item will be aligned vertically. This is the default.
list-style-position:inside; means bullet points will be inside the list item. As it is part of the list item, it will be part of the text and push the text at the start.
ul.a { list-style-position:outside; } ul.b { list-style-position:inside; }
ul { list-style-type:none; margin:0; padding:0; }
ul { list-style:square inside url("sqpurple.gif"); }
When using shorthand, the order of the property values are:
list-style-type ▶ if a list-style-image is specified, the value of this property will be displayed if the image for some reason cannot be displayed
list-style-position ▶ specifies whether list-item markers should appear inside or outside the content flow
list-style-image ▶ specifies an image as list item marker
If one of the property values above is missing, the default value for the missing property will be inserted, if any.
Can also style lists with colors, to make them look a more interesting.
Anything added to the <ol> or <ul> tag, affects the entire list, while properties added to <li> tag will affect individual list item:ol { background:#ff9999; padding:20px; } ul { background:#3399ff; padding:20px; }
All CSS List Properties | |
---|---|
Property | Description |
list-style | sets all properties for a list in one declaration |
list-style-image | specifies an image as list-item marker |
list-style-position | specifies position of the list-item markers ▶ bullet points |
list-style-type | specifies type of list-item marker |
more details/examples at:
table, th, td { border:1px solid black; }
Notice: When the above code is used the table will have double borders. This is because the table and the <th> and <td> elements have separate borders.
table { border-collapse:collapse; } table, th, td { border:1px solid black; }
table { border:1px solid black; }
table { width:100%; } th { height:50px; }
The text-align property sets the horizontal alignment:
By default, the content of <th> elements are center-aligned and the content of <td> elements are left-aligned.
th { text-align:left; }
The vertical-align property sets the vertical alignment:
By default, the vertical alignment of the content in a table is middle - for both <th> and <td> elements.
td { height:50px; vertical-align:bottom; }
th, td { padding:15px; text-align:left; }
th, td { border-bottom:1px solid #ddd; }
tr:hover { background-color:#f5f5f5; }
tr:nth-child(even) { background-color:#f2f2f2; }
th { background-color:#4CAF50; color:white; }
A responsive table will display a horizontal scroll bar if the screen is too small to display the full content.
Add a container element (like <div>) with overflow-x:auto around the <table> element to make it responsive:<div style="overflow-x:auto;"> <table> ... table content ... </table> </div>
📝 Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown when being used - even though overflow:scroll is set).
CSS Table Properties | |
---|---|
Property | Description |
border | sets all border properties in one declaration |
border-collapse | specifies whether or not table borders should be collapsed |
border-spacing | specifies distance between borders of adjacent cells |
caption-side | specifies placement of a table caption |
empty-cells | specifies whether or not to display borders and background on empty cells in a table |
table-layout | sets layout algorithm to be used for a table |
display property is the most important CSS property for controlling layout.
display property specifies if/how an element is displayed.
Every HTML element has a default display value depending on what type of element it is. The default display value for most elements is:
A block-level element always starts on a new line and takes up the full width available - stretches out to the left and right as far as it can.
Some block-level elements:
An inline element does not start on a new line and only takes up as much width as necessary.
Some inline elements:
display:none; is commonly used with javascript to hide and show elements without deleting and recreating them. This example shows this.
The <script> element uses display:none; as default.
As mentioned, every element has a default display value. However, it can be overriden.
Changing an inline element to a block element, or vice versa, can be useful for making the page look a specific way, and still follow the web standards.
A common example is making inline <li> elements for horizontal menus:li { display:inline; }
📝 Note: Setting the display property of an element only changes how the element is displayed, NOT what kind of element it is. So, an inline element with display:block; is not allowed to have other block elements inside it.
The following example displays <span> elements as block elements:span { display:block; }
h1.hidden { display:none; }
visibility:hidden; also hides an element.
However, the element will still take up the same space as before. The element will be hidden, but still affect the layout:h1.hidden { visibility:hidden; }
CSS Display/Visibility Properties | |
---|---|
Property | Description |
display | specifies how an element should be displayed |
visibility | specifies whether or not an element should be visible |
As mentioned before - a block-level element always takes up the full width available - stretches out to the left and right as far as it can.
Setting the width of a block-level element will prevent it from stretching out to the edges of its container. Then, the margins can be set to auto, to horizontally center the element within its container. The element will take up the specified width, and the remaining space will be split equally between the two margins.
📝 Note: A problem can happen with a <div> when the browser window is smaller than the width of the element. The browser will add a horizontal scrollbar to the page.
Using max-width in such a situation, will improve the browser's handling of small windows. This is important when making a site usable on small devices:div.ex1 { width:500px; margin:auto; border:3px solid #73AD21; } div.ex2 { max-width:500px; margin:auto; border:3px solid #73AD21; }
The position property specifies the type of positioning method used for an element:
Elements are then positioned using the properties:
However, these properties will not work unless the position property is set first. They also work differently depending on the position's value.
HTML elements are positioned static by default.
Static positioned elements are not affected by the properties:
An element with position:static; is not positioned in any special way - it is always positioned according to the normal flow of the page:
div.static { position:static; border:3px solid #73AD21; }
An element with position:relative; is positioned relative to its normal position.
Setting:
div.relative { position:relative; left:30px; border:3px solid #73AD21; }
An element with position:fixed; is positioned relative to the viewport,
which means it always stays in the same place even if the page is scrolled.
These properties:
A fixed element does not leave a gap in the page where it would normally have been located.
div.fixed { position:fixed; bottom:0; right:0; width:300px; border:3px solid #73AD21; }
An element with position:absolute; is positioned relative to the nearest positioned ancestor - instead of positioned relative to the viewport, like fixed.
However, if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
📝 Note: A positioned element is one whose position is anything except static.
div.absolute { position:absolute; top:80px; right:0; width:200px; height:100px; border:3px solid #73AD21; }
An element with position:sticky; is positioned based on the user's scroll position.
A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it sticks in place like position:fixed;.
📝 Note: Internet Explorer, Edge 15 and earlier versions do not support sticky positioning. Safari requires a -webkit-prefix (see example below). For sticky positioning to work use at least one of these properties:
The sticky element sticks to the top of the page (top: 0), when you reach its scroll position.
div.sticky { position:-webkit-sticky; /* Safari */ position:sticky; top:0; background-color:green; border:2px solid #4CAF50; }
When elements are positioned, they can overlap other elements.
The z-index property specifies the stack order of an element - which element should be placed in front of, or behind, others.
An element can have a positive or negative stack order:img { position:absolute; left:0px; top:0px; z-index:-1; }
An element with greater stack order is always in front of an element with a lower stack order.
📝 Note: If two positioned elements overlap without a z-index specified, the element positioned last in the HTML code will be shown on top.
🚴 w3schools Examples: Positioning Text In an Image
All CSS Positioning Properties | |
---|---|
Property | Description |
bottom | sets bottom margin edge for a positioned box |
clip | clips an absolutely positioned element |
left | sets left margin edge for a positioned box |
position | specifies type of positioning for an element |
right | sets right margin edge for a positioned box |
top | sets top margin edge for a positioned box |
z-index | sets the stack order of an element |
overflow property controls what happens to content that is too big to fit into an area.
overflow property specifies whether to clip the content or to add scrollbars when the content of an element is too big to fit in the specified area.
overflow property has the following values:
📝 Note: The overflow property only works for block elements with a specified height.
📝 Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown when being used - even though overflow:scroll is set.
div { width:200px; height:50px; background-color:#eee; overflow:visible; }
div { overflow:hidden; }
div { overflow:scroll; }
div { overflow:auto; }
The overflow-x and overflow-y properties specify whether to change the overflow of content just horizontally or vertically or both:
div { overflow-x:hidden; /* Hide horizontal scrollbar */ overflow-y:scroll; /* Add vertical scrollbar */ }
All CSS Overflow Properties | |
---|---|
Property | Description |
overflow | specifies what happens if content overflows an element's box |
overflow-x | specifies what to do with the left/right edges of the content if it overflows the element's content area |
overflow-y | specifies what to do with the top/bottom edges of the content if it overflows the element's content area |
The float property specifies how an element should float.
The clear property specifies what elements can float beside the cleared element and on which side.
float property is used for positioning and formatting content e.g. let an image float left to the text in a container.
float property can have one of the following values:
img { float:right; }
clear property specifies what elements can float beside the cleared element and on which side.
clear property can have one of the following values:
When clearing floats, you should match clear to float:
The following example clears the float to the left - means that no floating elements are allowed on the left side of the div:
div { clear:left; }
If an element is taller than the element containing it, and it is floated, it will overflow outside of its container:
.clearfix { overflow:auto; }
All CSS Float Properties | |
---|---|
Property | Description |
box-sizing | defines how width and height of an element are calculated: should they include padding and borders, or not |
clear | specifies what elements can float beside the cleared element and on which side |
float | specifies how an element should float |
overflow | specifies what happens if content overflows an element's box |
overflow-x | specifies what to do with the left/right edges of the content if it overflows the element's content area |
overflow-y | specifies what to do with the top/bottom edges of the content if it overflows the element's content area |
Compared to display:inline, the major difference is that display:inline-block allows setting width and height on an element:
Major difference between display:inline-block and display:block:
The following example shows the different behavior of:
span.a { display:inline; /* the default for span */ width:100px; height:100px; padding:5px; border:1px solid blue; background-color:yellow; } span.b { display:inline-block; width:100px; height:100px; padding:5px; border:1px solid blue; background-color:yellow; } span.c { display:block; width:100px; height:100px; padding:5px; border:1px solid blue; background-color:yellow; }
One common use for display:inline-block is to display list items horizontally instead of vertically. The following example creates horizontal navigation links:
.nav { background-color:yellow; list-style-type:none; text-align:center; padding:0; margin:0; } .nav li { display:inline-block; font-size:20px; padding:20px; }
Use margin:auto; ▶ to horizontally center a block element - like <div>.
Setting the width of an element prevents it from stretching out to the edges of its container.
The element will then take up the specified width, and the remaining space will be split equally between the two margins:
.center { margin:auto; width:50%; border:3px solid green; padding:10px; }
📝 Note: Center aligning has no effect if the width property is not set or set to 100%.
Use text-align:center; ▶ to just center the text inside an element.
.center { text-align:center; border:3px solid green; }
To center an image ▶ set left and right margin to auto and make it into a block element:
img { display:block; margin-left:auto; margin-right:auto; width:40%; }
One method for aligning elements is to use position:absolute;:
.right { position:absolute; right:0px; width:300px; border:3px solid #73AD21; padding:10px; }
📝 Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.
Another method for aligning elements is to use the float property:
.right { float:right; width:300px; border:3px solid #73AD21; padding:10px; }
📝 Note: If an element is taller than the element containing it, and it is floated, it will overflow outside of its container. You can use the clearfix hack to fix this.
Can add overflow:auto; to the containing element to fix overflow outside of its container:
.clearfix { overflow:auto; }
There are many ways to center an element vertically in CSS.
A simple solution is to use top and bottom padding:
.center { padding:70px 0; border:3px solid green; }
To center both vertically and horizontally, use padding and text-align:center:
.center { padding:70px 0; border:3px solid green; text-align:center; }
Another trick is to use the line-height property with a value that is equal to the height property:
.center { line-height:200px; height:200px; border:3px solid green; text-align:center; } /* If the text has multiple lines, add the following: */ .center p { line-height:1.5; display:inline-block; vertical-align:middle; }
If padding and line-height are not options, another solution is to use positioning and the transform property:
.center { height:200px; position:relative; border:3px solid green; } .center p { margin:0; position:absolute; top:50%; left:50%; transform:translate(-50%, -50%); }
📎 Tip: Learn more about transform property at 🎓 w3schools Advanced CSS 2D Transforms Chapter.
Can use flexbox to center things.
📝 Note: flexbox is not supported in IE10 and earlier versions.
A combinator is something that explains the relationship between selectors.
A CSS selector can contain more than one simple selector. Between the simple selectors, a combinator can be included.
There are four different combinators in CSS:
The descendant selector matches all elements that are descendants of a specified element.
The following example selects all <p> elements inside <div> elements:
div p { background-color:yellow; }
The child selector selects all elements that are the children of a specified element.
The following example selects all <p> elements that are children of a <div> element:
div > p { background-color:yellow; }
The adjacent sibling selector selects all elements that are the adjacent siblings of a specified element.
Sibling elements must have the same parent element, and adjacent means immediately following.
The following example selects all <p> elements that are placed immediately after <div> elements:
div + p { background-color:yellow; }
The general sibling selector selects all elements that are siblings of a specified element.
The following example selects all <p> elements that are siblings of <div> elements:
div ~ p { background-color:yellow; }
All CSS Combinator Selectors | ||
---|---|---|
Selector | Example | Example Description |
element element | div p | selects all <p> elements inside <div> elements |
element>element | div > p | selects all <p> elements where the parent is a <div> element |
element+element | div + p | selects all <p> elements that are placed immediately after <div> elements |
element1~element2 | p ~ ul | selects every <ul> element that are preceded by a <p> element |
A pseudo-class is used to define a special state of an element.
For example, it can be used to:
The syntax of pseudo-classes:
selector:pseudo-class { property:value; }
Links can be displayed in different ways:
/* unvisited link */ a:link { color:#FF0000; } /* visited link */ a:visited { color:#00FF00; } /* mouse over link */ a:hover { color:#FF00FF; } /* selected link */ a:active{ color: #0000FF; }
📝 Note: a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective! a:active MUST come after a:hover in the CSS definition in order to be effective! Pseudo-class names are not case-sensitive.
Pseudo-classes can be combined with CSS classes.
When you hover over the link in the example, it will change color:
a.highlight:hover { color:#ff0000; }
An example of using the :hover pseudo-class on a <div> element:
div:hover { background-color:blue; }
Hover over a <div> element to show a <p> element - like a tooltip:
p { display:none; background-color:yellow; padding:20px; } div:hover p { display:block; }
The :first-child pseudo-class matches a specified element that is the first child of another element.
In the following example, the selector matches any <p> element that is the first child of any element:
p:first-child { color: blue; }
In the following example, the selector matches the first <i> element in all <p> elements:
p i:first-child { color: blue; }
In the following example, the selector matches all <i> elements in <p> elements that are the first child of another element:
p:first-child i { color: blue; }
The :lang pseudo-class allows defining special rules for different languages.
In the example below, :lang defines the quotation marks for <q> elements with lang="no":
<html> <head> <style> q:lang(no) { quotes: "~" "~"; } </style> </head> <body> <p>Some text <q lang="no">A quote in a paragraph</q> Some text.</p>. </body> </html>
All CSS Pseudo Classes | ||
---|---|---|
Selector | Example | Example Description |
:active | a:active | selects the active link |
:checked | input:checked | selects every checked <input> element |
:disabled | input:disabled | selects every disabled <input> element |
:empty | p:empty | selects every <p> element that has no children |
:enabled | input:enabled | selects every enabled <input> element |
:first-child | p:first-child | selects every <p> elements that is the first child of its parent |
:first-of-type | p:first-of-type | selects every <p> element that is the first <p> element of its parent |
:focus | input:focus | selects the <input> element that has focus |
:hover | a:hover | selects links on mouse over |
:in-range | input:in-range | selects <input> elements with a value within a specified range |
:invalid | input:invalid | selects all <input> elements with an invalid value |
:lang(language) | p:lang(it) | selects every <p> element with a lang attribute value starting with "it" |
:last-child | p:last-child | selects every <p> elements that is the last child of its parent |
:last-of-type | p:last-of-type | selects every <p> element that is the last <p> element of its parent |
:link | a:link | selects all unvisited links |
:not(selector) | :not(p) | selects every element that is not a <p> element |
:nth-child(n) | p:nth-child(2) | selects every <p> element that is the second child of its parent |
:nth-last-child(n) | p:nth-last-child(2) | selects every <p> element that is the second child of its parent, counting from the last child |
:nth-last-of-type(n) | p:nth-last-of-type(2) | selects every <p> element that is the second <p> element of its parent, counting from the last child |
:nth-of-type(n) | p:nth-of-type(2) | selects every <p> element that is the second <p> element of its parent |
:only-of-type | p:only-of-type | selects every <p> element that is the only <p> element of its parent |
:only-child | p:only-child | selects every <p> element that is the only child of its parent |
:optional | input:optional | selects <input> elements with no "required" attribute |
:out-of-range | input:out-of-range | selects <input> elements with a value outside a specified range |
:read-only | input:read-only | selects <input> elements with a "readonly" attribute specified |
:read-write | input:read-write | selects <input> elements with no "readonly" attribute |
:required | input:required | selects <input> elements with a "required" attribute specified |
:root | root | selects the document's root element |
:target | #news:target | selects the current active #news element (clicked on a URL containing that anchor name) |
:valid | input:valid | selects all <input> elements with a valid value |
:visited | a:visited | selects all visited links |
A CSS pseudo-element is used to style specified parts of an element.
For example, it can be used to:
selector::pseudo-element { property:value; }
The ::first-line pseudo-element is used to add a special style to the first line of a text.
The following example formats the first line of the text in all <p> elements:
p::first-line { color:#ff0000; font-variant:small-caps; }
📝 Note: The ::first-line pseudo-element can only be applied to block-level elements.
The following properties apply to the ::first-line pseudo-element:
Notice the double colon notation - ::first-line versus :first-line:
The double colon replaced the single-colon notation for pseudo-elements in CSS3. This was an attempt from W3C to distinguish between pseudo-classes and pseudo-elements.
The single-colon syntax was used for both pseudo-classes and pseudo-elements in CSS2 and CSS1.
For backward compatibility, the single-colon syntax is acceptable for CSS2 and CSS1 pseudo-elements.
The ::first-letter pseudo-element is used to add a special style to the first letter of a text.
The following example formats the first letter of the text in all <p> elements:
p::first-letter { color:#ff0000; font-size:xx-large; }
📝 Note: The ::first-letter pseudo-element can only be applied to block-level elements.
The following properties apply to the ::first-letter pseudo-element:
Pseudo-elements can be combined with CSS classes:
/*will display the first letter of paragraphs with class="intro", in red and in a larger size.*/ p.intro::first-letter { color:#ff0000; font-size:200%; }
Several pseudo-elements can also be combined.
/* -the first letter of a paragraph will be red in an xx-large font size -the rest of the first line will be blue, and in small-caps -the rest of the paragraph will be the default font size and color */ p::first-letter { color:#ff0000; font-size:xx-large; } p::first-line { color:#0000ff; font-variant:small-caps; }
The ::before pseudo-element can be used to insert some content before the content of an element.
/*inserts an image before the content of each <h1> element*/ h1::before { content:url(smiley.gif); }
The ::after pseudo-element can be used to insert some content after the content of an element.
/*inserts an image after the content of each <h1> element*/ h1::after { content:url(smiley.gif); }
The ::selection pseudo-element matches the portion of an element that is selected by a user.
The following CSS properties can be applied to ::selection:
/*makes the selected text red on a yellow background*/ ::selection { color:red; background:yellow; }
All CSS Pseudo Elements | ||
---|---|---|
Selector | Example | Example Description |
::after | p::after | insert content after every <p> element |
::before | p::before | insert content before every <p> element |
::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 |
::selection | p::selection | selects the portion of an element that is selected by a user |
The opacity property specifies the opacity/transparency of an element.
🚴 w3schools CSS Opacity/Transparency Tutorial
There are 5 sections with examples explaining how to do:
🚴 w3schools CSS Navigation Bar Tutorial
Having easy-to-use navigation is important for any web site.
With CSS you can transform boring HTML menus into good-looking navigation bars.
A navigation bar uses standard HTML as a base.
The examples show how to build navigation bars from a standard HTML list.
🚴 w3schools CSS Vertical Navigation Bar Tutorial
<style> /* Step 1: remove the bullets and the margins and padding from the list makes a vertical nav bar*/ ul { list-style-type:none; margin:0; padding:0; } /* Step 2: style the <a> elements inside the list */ li a { display:block; width:60px; } /* display:block; - Displaying the links as block elements makes the whole link area clickable (not just the text), and it allows us to specify the width (and padding, margin, height, etc. if you want) width:60px; - Block elements take up the full width available by default. We want to specify a 60 pixels width */ </style> <!--sart with <ul> and <li> elements--> <ul> <li><a href="default.asp">Home</a></li> <li><a href="news.asp">News</a></li> <li><a href="contact.asp">Contact</a></li> <li><a href="about.asp">About</a></li> </ul>
Add an active class to the current link to let the user know which page he/she is on:
.active { background-color:#4CAF50; color:white; }
Add text-align:center to <li> or <a> to center the links.
Add the border property to <ul> to add a border around the navbar. If you also want borders inside the navbar, add a border-bottom to all <li> elements, except for the last one:
ul { border:1px solid #555; } li { text-align:center; border-bottom:1px solid #555; } li:last-child { border-bottom:none; }
Create a full-height, sticky side navigation:
ul { list-style-type:none; margin:0; padding:0; width:25%; background-color:#f1f1f1; height:100%; /* Full height */ position:fixed; /* Make it stick, even on scroll */ overflow:auto; /* Enable scrolling if the sidenav has too much content */ }
🚴 w3schools CSS Horizontal Navigation Bar Tutorial
There are two ways to create a horizontal navigation bar:
One way to build a horizontal navigation bar is to specify the <li> elements as inline, in addition to the code from CSS Vertical Navigation Bar example:
/* display: inline; - By default, <li> elements are block elements. Here, we remove the line breaks before and after each list item, to display them on one line */ li { display:inline; }
Another way of creating a horizontal navigation bar is to float the <li> elements, and specify a layout for the navigation links:
li { float:left; } a { display:block; padding:8px; background-color:#dddddd; }
📝 Note: If a !DOCTYPE is not specified, floating items can produce unexpected results.
Example explained:
float:left; ▶ use float to get block elements to slide next to each other
display:block; ▶ displaying the links as block elements makes the whole link area clickable - not just the text, and it allows specifying padding - and height, width, margins, etc. if wanted
padding:8px; ▶ since block elements take up the full width available, they cannot float next to each other - therefore, specify some padding to make them look good
background-color:#d3d3d3; ▶ add a lightgrey background-color to each a element
📎 Tip: Add the background-color to <ul> instead of each <a> element if you want a full-width background color.
/* 1. basic horizontal navigation bar 2. with a dark background color 3. change the background color of the links when the user moves the mouse over them */ ul { list-style-type:none; margin:0; padding:0; overflow:hidden; background-color:#333; } li { float:left; } li a { display:block; color:white; text-align:center; padding:14px 16px; text-decoration:none; } /* Change the link color to #111 (black) on hover */ li a:hover { background-color:#111; }
/* Add an "active" class to the current link to let the user know which page is showing: */ .active { background-color:#4CAF50; }
<!-- Right-align links by floating the list items to the right (float:right;): --> <ul> <li><a href="#home">Home</a></li> <li><a href="#news">News</a></li> <li><a href="#contact">Contact</a></li> <li style="float:right"><a class="active" href="#about">About</a></li> </ul>
/* Add the border-right property to <li> to create link dividers Add a gray right border to all list items, except the last item (last-child) */ li { border-right:1px solid #bbb; } li:last-child { border-right:none; }
/*Fixed Top*/ ul { position:fixed; top:0; width:100%; } /*Fixed Bottom*/ ul { position:fixed; bottom:0; width:100%; }
📝 Note: Fixed position might not work properly on mobile devices.
/*gray horizontal navigation bar with a thin gray border*/ ul { border:1px solid #e7e7e7; background-color:#f3f3f3; } li a { color:#666; }
Add position:sticky; to <ul> to create a sticky navbar.
A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it sticks in place like position:fixed.
ul { position:-webkit-sticky; /* Safari */ position:sticky; top: 0; }
📝 Note: Internet Explorer, Edge 15 and earlier versions do not support sticky positioning. Safari requires a -webkit- prefix -see example above. Must also specify at least one of:
🚴 w3schools CSS Horizontal Navigation Bar Tutorial examples near bottom of page above ads
🚴 w3schools CSS Dropdowns Tutorial
🚴 w3schools CSS Image Gallery Tutorial
CSS can be used to create an image gallery.
🚴 w3schools CSS Image Sprites Tutorial
An image sprite is a collection of images put into a single image.
A web page with many images can take a long time to load and generates multiple server requests.
Using image sprites will reduce the number of server requests and save bandwidth.
It is possible to style HTML elements with attributes.
The [attribute] selector is used to select elements with a specific attribute.
/* select all <a> elements with a target attribute */ a[target] { background-color:yellow; }
The [attribute="value"] selector is used to select elements with a specific attribute and value.
/* select all <a> elements with a target="_blank" attribute */ a[target="_blank"] { background-color:yellow; }
The [attribute~="value"] selector is used to select elements with an attribute value containing a specific word.
/* select all elements with a title attribute that contains a space-separated list of words, one of which is "flower" will match elements with title="flower", title="summer flower", and title="flower new", but not title="my-flower" or title="flowers" */ [title~="flower"] { border:5px solid yellow; }
The [attribute|="value"] selector is used to select elements with the specified attribute starting with the specified value.
/* select all elements with a class attribute value that begins with "top" *** Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text"! */ [class|="top"] { background:yellow; }
The [attribute^="value"] selector is used to select elements whose attribute value begins with a specific value.
/* select all elements with a class attribute value that begins with "top" *** Note: The value does not have to be a whole word! */ [class^="top"] { background:yellow; }
The [attribute$="value"] selector is used to select elements whose attribute value ends with a specific value.
/* select all elements with a class attribute value that ends with "test" *** Note: The value does not have to be a whole word! */ [class$="test"] { background:yellow; }
The [attribute*="value"] selector is used to select elements whose attribute value contains a specifiec value.
/* select all elements with a class attribute value that contains "te" *** Note: The value does not have to be a whole word! */ [class*="te"] { background:yellow; }
/* attribute selectors can be useful for styling forms without class or ID */ input[type="text"] { width:150px; display:block; margin-bottom:10px; background-color:yellow; } input[type="button"] { width:120px; margin-left:35px; display:block; }
📎 Tip: Visit 🚴 w3schools CSS Forms Tutorial for more examples on how to style forms with CSS.
All CSS Attribute Selectors | ||
---|---|---|
Selector | Example | Example Description |
[attribute] | [target] | selects all elements with a target attribute |
[attribute=value] | [target=_blank] | selects all elements with target="_blank" |
[attribute~=value] | [title~=flower] | selects all elements with a title attribute containing the word "flower" |
[attribute|=value] | [lang|=en] | selects all elements with a lang attribute value starting with "en" |
[attribute^=value] | a[href^="https"] | selects every <a> element whose href attribute value begins with "https" |
[attribute$=value] | a[href$=".pdf"] | selects every <a> element whose href attribute value ends with ".pdf" |
[attribute*=value] | a[href*="w3schools"] | selects every <a> element whose href attribute value contains the substring "w3schools" |
The look of a HTML form can be greatly improved with CSS
./* this width property determines width of all input fields */ input { width:100%; }
Examples of styling specific input types using attribute selectors:
/* padding property adds space inside the text field *** Tip: if many inputs after each other, can add some margin, to separate them more */ input[type=text] { width:100%; padding:12px 20px; margin:8px 0; box-sizing:border-box; }
📝 Note: In the above example, the box-sizing property is set to border-box. This makes sure that the padding and eventually borders are included in the total width and height of the elements. Read more about the box-sizing property at 🎓 w3schools Advanced CSS Box Sizing Tutorial
/* Use the border property to change the border size and color use the border-radius property to add rounded corners */ input[type=text] { border:2px solid red; border-radius:4px; }
If you only want a bottom border, use the border-bottom property.
/* Use background-color property to add a background color to the input use the color property to change the text color */ input[type=text] { background-color:#3CBC8D; color:white; }
By default, some browsers will add a blue outline around the input when it gets focus clicked on. You can remove This behavior can be removed by adding outline:none; to the input.
/* Use the :focus selector to do something with the input field when it gets focus */ input[type=text]:focus { background-color:lightblue; } /* or */ input[type=text]:focus { border:3px solid #555; }
If you want an icon inside the input, use the background-image property and position it with the background-position property. Also notice a large left padding was added to reserve the space of the icon:
input[type=text] { background-color:white; background-image:url('searchicon.png'); background-position:10px 10px; background-repeat:no-repeat; padding-left:40px; }
/* use transition property to animate width of the search input area when it gets focus */ input[type=text] { transition:width 0.4s ease-in-out; } input[type=text]:focus { width:100%; }
Learn more about transition property at 🎓 w3schools Advanced CSS Transitions Tutorial
📎 Tip: Use the resize property to prevent textareas from being resized ▶ disables grabber at the bottom right corner of the textarea.
textarea { width:100%; height:150px; padding:12px 20px; box-sizing:border-box; border:2px solid #ccc; border-radius:4px; background-color:#f8f8f8; resize:none; }
can size attrubute be set through css?
select { width:100%; padding:16px 20px; border:none; border-radius:4px; background-color:#f1f1f1; }
/* Tip: use width:100% for full-width buttons */ input[type=button], input[type=submit], input[type=reset] { background-color:#4CAF50; border:none; color:white; padding:16px 32px; text-decoration:none; margin:4px 2px; cursor:pointer; }
Read more about how to style buttons with CSS at 🎓 w3schools Advanced CSS Buttons Tutorial
When resizing browser window due to device size or user actions form layout can be adjusted to look better.
Advanced: Read about using media queries to create a responsive form at 🎓 w3schools Advanced CSS Media Queries Tutorial
CSS counters are variables maintained by CSS whose values can be incremented by CSS rules - to track how many times they are used. Counters allow adjusting the appearance of content based on its placement in the document.
To work with CSS counters use the following properties:
To use a CSS counter, it must first be created with counter-reset.
The following example creates a counter for the page in the body selector, then increments the counter value for each <h2> element and adds Section <value of the counter>: to the beginning of each <h2> element:
body { counter-reset:section; } h2::before { counter-increment:section; content:"Section " counter(section) ": "; }
The following example creates one counter for the page section and one counter for each <h1> element subsection. The section counter will be counted for each <h1> element with Section <value of the section counter>., and the subsection counter will be counted for each <h2> element with <value of the section counter>.<value of the subsection counter>:
body { counter-reset:section; } h1 { counter-reset:subsection; } h1::before { counter-increment:section; content:"Section " counter(section) ". "; } h2::before { counter-increment:subsection; content:counter(section) "." counter(subsection) " "; }
A counter can also be useful to make outlined lists because a new instance of a counter is automatically created in child elements. Here counters() function is used to insert a string between different levels of nested counters:
ol { counter-reset:section; list-style-type:none; } li::before { counter-increment:section; content:counters(section,".") " "; }
CSS Counter Properties | |
---|---|
Property | Description |
content | used with the ::before and ::after pseudo-elements, to insert generated content |
counter-increment | increments one or more counter values |
counter-reset | creates or resets one or more counters |
CSS has several different units for expressing a length.
Length is a number followed by a length unit, such as 10px, 2em, etc.
📝 Note: A whitespace cannot appear between the number and the unit.
However, if the value is 0, the unit can be omitted.
For some CSS properties, negative lengths are allowed.
There are two types of length units:
The absolute length units are fixed and a length expressed in any of these will appear as exactly that size.
Absolute length units are not recommended for use on screen, because screen sizes vary so much. However, they can be used if the output medium is known, such as for print layout.
Unit | Description |
---|---|
cm | centimeters |
mm | millimeters |
in | inches ▶ 1in = 96px = 2.54cm |
px Note 1 | pixels ▶ 1px = 1/96th of 1in |
pt | points ▶ 1pt = 1/72 of 1in |
pc | picas ▶ 1pc = 12 pt |
📝 Note 1: 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.
Relative length units specify a length relative to another length property. Relative length units scales better between different rendering mediums.
Unit | Description |
---|---|
em | relative to the font-size of the element - 2em means 2 times the size of the current font |
ex | relative to the x-height of the current font - rarely used |
ch | relative to width of the 0 zero |
rem | relative to font-size of the root element |
vw | relative to 1% of the width of the viewport Note 2 |
vh | relative to 1% of the height of the viewport Note 2 |
vmin | relative to 1% of viewport's Note 2 smaller dimension |
vmax | relative to 1% of viewport's Note 2 larger dimension |
% | relative to the parent element |
📎 Tip: The em and rem units are practical in creating perfectly scalable layout!
📝 Note 2: Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm.
If there are two or more conflicting CSS rules that point to the same element, the browser follows some rules to determine which one is most specific and therefore wins out.
Specificity is a score/rank that determines which style declarations are ultimately applied to an element.
The universal selector * has low specificity, while ID selectors are highly specific!
📝 Note: Specificity is a common reason why CSS rules don't apply to some elements in the order desired.
Every selector has its place in the specificity hierarchy.
There are four categories which define the specificity level of a selector: | ||
---|---|---|
Category | Description | Example |
Inline styles | an inline style is attached directly to the element to be styled | <h1 style="color: #ffffff;"> |
IDs | an ID is a unique identifier for the page elements | #navbar. |
Classes, attributes and pseudo-classes |
this category includes:
|
:hover :focus |
Elements and pseudo-elements |
this category includes:
|
h1 div :before :after |
Memorize how to calculate specificity!
There are 5 steps to calculating specificity:
Consider these three code fragments: | |||
---|---|---|---|
Code Fragment | Specificity | Category | |
A | h1 | 1 | one element |
B | #content h1 | 101 | one ID reference and one element |
C |
<div id="content"> <h1 style="color:#ffffff">Heading</h1> </div> |
1000 | inline styling |
Since 1 < 101 < 1000, the third rule C has a greater level of specificity, and therefore will be applied. |
Equal specificity: the latest rule counts.
If the same rule is written twice in the external style sheet, then the lower rule in the style sheet is
closer to the element to be styled, and therefore will be applied.
Example:
h1 {background-color:yellow;} h1 {background-color:red;} /*this rule is always applied.*/
ID selectors have a higher specificity than attribute selectors.
Look at the following three code lines:
/*this rule is more specific than other two therefore it will be used*/ div#a { background-color:green; } #a { background-color:yellow; } div[id=a] { background-color:blue; }
Contextual selectors are more specific than a single element selector.
The embedded <style></style> is closer to the element than an external CSS file for any elements being styled. Therefore in the following situation:
From external CSS file:
#content h1 { background-color:red; }
In HTML file:
<style> #content h1 { background-color:yellow; /*this rule will be applied*/ } </style>
A class selector beats any number of element selectors ▶ a class selector such as .intro beats h1, p , div, etc.:
/* .intro rule beats h1 rule */ .intro { background-color:yellow; } h1 { background-color:red; }
The universal selector and inherited values have a specificity of 0 ▶ * , body * and similar have zero specificity. Inherited values also have a specificity of 0.