CSS Cheat Sheet for Beginners and Advanced Users

This comprehensive CSS cheat sheet covers everything you need to know to style your web pages, from basic syntax to advanced concepts like CSS variables and CSS grids. It's also a great resource for experienced CSS users who want to brush up on their skills or learn something new.

📓 15 Best CSS Books for Beginners and Advanced Coders

INTRODUCTION TO CSS

To specify formatting within an HTML document (fonts, layout, background, colours, etc. ), authors have to apply separate tags to different parts to format. The term CSS pertains to Cascading Style Sheets, which are used to specify your document's style. While HTML is utilized for structuring a web page (the headlines and paragraphs, as well as the ability to include images, video, and other elements), CSS specifies your page layout, colours, and fonts. CSS is used to bring style to your web pages.

TYPES OF CSS: 

There are 3 types of CSS 

  1. External CSS
  2. Internal CSS
  3. Inline CSS

1. External CSS: For using an external style sheet, your .html files need to include a header section that links to an external style sheet. Since the CSS code is in a separate document, your HTML files will have a cleaner structure and are smaller in size.

You can use the same .css file for multiple pages.

For example:

<head>
<link rel=”stylesheet”  type=”text/css”  href=mysitestyle.css”>
</head>

2. Internal CSS: These CSS instructions are written directly into the header of a specific .html page. This CSS style is an effective method of styling a single page.

For example:

<head>
<style>
Body  {  background-color:thistle;  }
P  {  font-size:20px;  color:mediumblue;  }
</style>
</head>

3. Inline CSS: Lastly, inline styles are CSS blocks that are written directly into a single instance of HTML code.

For example:

<h1  style=”font-size:55px;color:orange;”>Check out this headline!</h1>

The most efficient way of implementing CSS on a website is to use external style sheets, whereas internal style sheets and inline styles are suitable for case-by-case changes.

What is CSS Syntax?

CSS syntax is relatively simple. Various attributes, such as font size and background colour, are assigned values within the brackets following the name of the element to style, called the CSS selector.

What are CSS Selectors?

A CSS property value pattern is a pattern of elements, such as HTML elements, that instruct the browser which elements to select when applying the CSS property values.

Learn CSS: Basics to Advanced Concepts

1. CSS Selectors

COMMANDDESCRIPTIONSYNTAX
UNIVERSAL SELECTORThe CSS universal selector (*) matches elements of any type. When utilising @namespace, universal selectors can be namespaced.
{}
ID SELECTORThe CSS ID selector matches an element based on the value of the element’s id attribute. This is what you'd use to refer to that one-of-a-kind element with an id.
id {}
CLASS SELECTORThe CSS class selector matches elements based on the contents of their class. 
.class {}
TYPE SELECTORIt selects all elements of the given type within a document. In other words, the type selector in CSS matches components based on their node names.
h1, h2 ,h3 {}
ADJACENT SIBLING SELECTORThe adjacent sibling combinator (+) separates two selectors. It comes right after the first element, and they're both children of the same parent.
h1 + p {}
CHILD SELECTORThe child combinator (>) is placed between two CSS selectors.
ul > li {}
GENERAL SIBLING SELECTORSelect all elements that follow the first element such that both are children of the same parent.
h1 ~ p {}
DESCENDANT SELECTORAny selector with white space between two selectors without a combinator.
p a {}

2. Pseudo-classes and Pseudo-elements

A pseudo-class is used to define a special state of an element. A CSS pseudo-element is used to style specified parts of an element.

COMMANDSDESCRIPTIONSYNTAX
Mouse over selectorTriggered when the user hovers over an element with the cursor. You can use the hover selection to target an element that a user hovers over with their cursor.
a:hover {}
Active Link SelectorThe :active pseudo-class is commonly used on <a> and <button> elements. When a link is clicked, you can provide a style for it with this selector.
a:active {}
Focus SelectorTriggered when the user clicks or taps on an element or selects it with the keyboard's Tab key.
input:focus {}
Visited Links SelectorRepresents that the link has already been visited. Its styles for URLs that the user has already visited are defined.
:visited {}
Link Selector This represents that the link has not yet been visited.
.class:link {}
Checked selector elementRepresents radio, checkbox, or option element that is checked or toggled to an on-state. When the page loads, it specifies that an <input> element should be already selected (checked).
input:checked {}
Disabled elements selectorAn element is disabled. It represents that the element is currently disabled, To pick the disabled element, the :disabled selector is used.
input:disabled {}
Enabled elements selectorAn element is enabled. It represents that the element is currently available.
input:enabled {}
Not a Specified Element SelectorRepresents elements that do not match a list of selectors.
:not(p) {}
First Line SelectorApplies styles to the first line of a block-level element. It is used in the first line of an element to style it.
p::first-line {}
First Letter SelectorApplies styles to the first letter of the first line. The style is applied to the first letter of the first line of a block-level element if it is not preceded by other content.
::first-letter {}
First Child SelectorRepresents the first element among a group of sibling elements. It is used to find all elements that are children of a given element.
:first-child {}
Last Child SelectorRepresents the last. It indicates the last sibling element in a collection of siblings.
:last-child {}
Only Child SelectorRepresents an element without any siblings. You can use the CSS:only-child selector to target an element which is the only child of its parent.
:only-child {}
:nth-child SelectorMatches elements based on their position.
:nth-child()
First Element of its Parent Selector Represents the first element. In CSS, you may use the:first-of-type selector to target an element's first appearance within the container.
P:first-of-type {}
Elements that have no Children SelectorRepresents any element that has no children. Any element with no children is represented by this. Either element nodes or text can be children.
p:empty {}
Before ElementUsed to add cosmetic content to an element with the content property.The::before pseudo-element is used to define created stuff that comes before the content of an element.
class::before {}
After ElementUsed to add cosmetic content to an element with the content propertyThe::after pseudo-element is used to define created stuff that comes after the content of an element.
.class::after {}

3. CSS Text Styling

COMMANDDESCRIPTIONSYNTAX 
Font styleIt sets the font style. We can set our text as normal, bold, italic, oblique as per our requirement
font-style: normal | italic | oblique
Font VariantIt sets the font variation. We can set the variant of the font as uppercase or lowercase, small-caps etc as per required by the user. 
font-variant: normal | small-caps
Font WeightSets the font weight. It helps us to set the weight of the font as normal, bold,  bolder lighter and we can also set it in numerics.
font-weight: normal | bold | bolder | lighter | 100 - 900
Vertical AlignmentSets the alignment i.e. where text is shown. It will help to adjust our text where it will appear.
vertical-align: baseline | 10px | sub | super | top | text-top | middle | bottom | text-bottom | initial
Text TransformIt sets how text is written. It will define the text as uppercase, lowercase or capitalized.
text-transform: capitalise | lowercase | uppercase
Font SizeIt sets the font size. It helps us to define the size of our font to make our web page more attractive.
font-size: 12px | 0.8em | 80%
Space Between CharactersIt defines the space between characters. It helps to adjust the spacing between two characters.
letter-spacing: normal | 4px
Line HeightIt sets the height of the line. It defines the height of the line.
line-height: normal | 3em | 34%
Horizontal AlignmentSets the horizontal alignment of the content. It helps to align the text horizontally whether it is left, right, centre or align.
text-align: left | right | center | justify
Text Align LastThe text-align-last CSS property specifies how the last line of a block or line should be oriented before a forced line break.
text-align-last: auto | left | right | center | justify | start | end | initial | inherit
Text DecorationText-decoration-line, text-decoration-color, text-decoration-style, and the newer text-decoration-thickness are all shorthand for this property.
text-decoration: none | underline | overline | line-through
Indent First Line The indentation of the initial line in a text block is controlled by the text-indent attribute.
 text-indent: 25px
Font FamilySets the font family of the text by linking the font families from google to the HTML.
font-family: 'Open Sans', sans-serif
Text JustifySpecifies the justification method of text when text-align is set to "justify".
text-justify: auto | inter-word | inter-character | none
Text OverflowSets how hidden overflow content is signalled to the user.
text-overflow: clip | ellipsis | string | initial | inherit
Text ShadowSets the shadow of text in any direction.
text-shadow: h-shadow v-shadow blur-radius color | none | initial | inherit

4. CSS Table

COMMANDDESCRIPTIONSYNTAX
Adding Borders to TablesThe CSS border property is the best way to define the borders for the tables.
border: 1px solid black;
Adjusting spacing inside TablesYou may easily use the CSS padding property to provide additional space between the table cell contents and the cell borders.
th, td {padding: 15px;}
Setting Table Width and HeightThe width and height CSS properties can also be used to specify the table's width and height, as well as the width and height of its cells.
table {width: 100%;}  |  th {height: 40px;}
Controlling table layoutThis property specifies the layout algorithm for table cells, rows, and columns.
 table { width: 300px; table-layout: fixed; }
Horizontal Alignment of Cell ContentsYou may use the text-align property in the same manner you do with other components to position text inside table cells horizontally.
th {text-align: left;}
Vertical Alignment of Cell ContentsSimilarly, you may use the CSS vertical-align property to align the content inside the th> and td> elements to the top, bottom, or center.
th {height: 30px; vertical-align: bottom;}
Making a Table ResponsiveTables aren't naturally responsive. You may add responsiveness to your tables by allowing horizontal scrolling on tiny displays to support mobile devices. Simply enclose your table in a div> element and use the overflow-x: auto; style.
<div style="overflow-x: auto;"> 
    <table>
        ... table content ...
    </table>
</div>

5. CSS Position

COMMANDDESCRIPTIONSYNTAX
PositionSet the position of the elements in a document.
position: static | relative | absolute | fixed | sticky
Position PropertiesDefines the position of an element in a document.
top | right | bottom | left
Float ElementDefines the position of an element in a document text and inline elements to wrap around.
float: left | right | none
Clear Floating ElementsWhether an element must be moved below (cleared) floating elements that precede it.
clear: none | left | right | both
Z IndexSets overlapping elements with a larger z-index cover those with a smaller one.
z-index: 3 | auto | inherit

6. CSS Background

COMMANDSDESCRIPTIONSYNTAX
Background ImageSets the background image in a div. An element's background-image attribute specifies one or more background images.
background-image: url()
Background RepeatSets whether the background is to be repeated or not, in other words, it determines whether or not the background picture will be repeated.
background-repeat: repeat-x | repeat-y | repeat | space | round | no-repeat
Background AttachmentSets the background image scroll or fixed. CSS's background-attachment attribute controls how the background moves in relation to the viewport.
background-attachment: scroll | fixed | local | initial | inherit
Background Color Set the background colour of the div or container.
background-color: #2AA9E0
Background PositionSets the position of the background.
background-position: top | right | bottom | left | center
Background OpacityThe opacity property specifies the opacity/transparency of an element. It can take a value from 0.0 - 1.0. The lower value, the more transparent it is.
div {background-color: green; and opacity: 0.3};

Different properties and how it works:

7. CSS Box Model

COMMANDDESCRIPTIONSYNTAX
Box SizingSets the width and height of the box. Building CSS layouts with the box-sizing property may be a lot more straightforward.
box-sizing: border-box | content-box
MarginSets the margin from all the sides of the box. This CSS tutorial explains how to use the CSS property called margin with syntax and examples.
margin: 2px 4px 6px 8px | 0 auto | inherit
PaddingSets the area inside the box from the content. CSS's box-sizing attribute determines how the box model is applied to the element to which it applies.
padding: 2px 4px 6px 8px | 100% | inherit |
Border Color Sets the colour of the border of the box.
border-color: #2AA9E0
Border Style Sets the style of the border.
border-style: none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset
Border WidthSets the width of the border. The width of an element's borders is determined by the border-width attribute. The value of this characteristic can range from one to four.
border-width: 10px

For example, in the following code,

img{
      Border-radius: 8px:
}

The output will look like the below:

For this code 

img{
     Border-radius: 50px:
}

Output for the above code looks like the below:

8. CSS Styling Lists

COMMANDSDESCRIPTIONSYNTAX
List TypeIt sets the type of list. The List is of many types. You can select the type of list you want to add whether it is an ordered or unordered list.
list-style-type: disc | circle | square | none
List PositionSets the position of the list.
list-style-position: inside | outside
List ImageSets the background image of the list.
list-style-image: url()

9. CSS Flexbox

COMMANDDESCRIPTIONSYNTAX
Flex DirectionSets how flex items are placed in the flex container.
flex-direction: row | row-reverse | column | column-reverse
Flex WrapSets whether flex items are forced onto one line or can wrap onto multiple lines.
flex-wrap: nowrap | wrap | wrap-reverse
Justify ContentDefines how the browser distributes space between and around content items.
justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly
Align ItemsIt sets the align-self value on all direct children as a group.
gn-items: flex-start | flex-end | center | baseline | stretch
Align ContentSets the distribution of space between and around content.
align-content: flex-start | flex-end | center | space-between | space-around | stretch
OrderSets the order to lay out an item in a flex or grid container.
order: 0
Flex GrowIt sets the flex-grow factor. Flex-grow is a term that refers to a system that allows you to The flex-grow factor of a flex item's main size to be controlled by the CSS property flex grow factor. 
flex-grow: 0
Flex ShrinkIt sets the flex shrink factor of a flex item. The flex-shrink is a method of reducing the size of a flexible object The flex-shrink factor of a flex item is controlled by the CSS attribute.
flex-shrink: 0
Flex BasisSets the size of the content box. The flex-basis is a system that allows you to change your mind at any A flex item's initial primary size is determined by a CSS attribute. Unless box-sizing is used, it determines the size of the content box.
flex-basis: 3px | auto
Align SelfIt aligns the item inside the grid area.
gn-self: auto | flex-start | flex-end | center | baseline | stretch

Let's understand flexbox with an example:

 Code:
.flex-container {
    display: flex;
}

Output:  

10. CSS Grid

COMMANDDESCRIPTIONSYNTAX
Grid Template ColumnsSpecifies the size of the columns, and how many columns are in a grid layout.
d-template-columns: 40px 50px auto 50px 40px
Grid Template RowsSpecifies the size of the rows in a grid layout.
grid-template-rows: 25% 100px auto
Grid Template AreasSpecifies how to display columns and rows, using named grid items.
grid-template-areas: "a b c" | none
Grid TemplateProperty for defining grid columns, rows, and areas.
grid-template: "a a a" 20% "b b b" auto | 100px 1fr / 50px 1fr
Grid Column GapSets the size of the gap between columns.
grid-template: "a a a" 20% "b b b" auto | 100px 1fr / 50px 1fr
Grid Row GapIt sets the size of the gap between an element's grid rows. The space between rows is known as the row gap. The gap between an element's grid rows is controlled by this attribute.
grid-row-gap: 10px
Justify ItemsDefines the default justify-self for all items of the box.
justify-items: start | end | center | stretch
Align ItemsSets the align-self value on all direct children as a group.
align-items: start | end | center | stretch
Justify ContentSpecifies how the browser distributes space between and around content.
justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly
Align ContentDistribution of space between and around content items.
justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly
Grid Auto ColumnsSpecifies the size of an implicitly-created grid column track or pattern of tracks.
grid-auto-columns: 100px | max-content | min-content
Grid Auto RowsCSS property specifies the size of an implicitly-created grid row track or pattern of tracks.
grid-auto-rows: 100px | max-content | min-content
Grid Auto FlowProperty controls how the auto-placement algorithm works.
grid-auto-flow: row | column | row dense | column dense
Grid Column StartCSS property specifies a grid item’s start position within the grid column.
grid-column-start: 2 | areaname | span 2 | span areaname | auto
Grid Column EndSpecifies a grid item’s start position within the grid column by contributing a line, a span.
grid-column-end: 2 | areaname | span 2 | span areaname | auto
Grid Row StartA grid item’s start position within the grid row by contributing a line.
grid-row-start: 2 | areaname | span 2 | span areaname | auto
Grid Row EndSpecifies a grid item’s end position within the grid row by contributing a line.
grid-row-end: 2 | areaname | span 2 | span areaname | auto
Grid Column Specifies a grid item's size and location within a grid column by contributing a line.
grid-column: 3 / span 2
Grid RowSpecifies a grid item’s size and location within the grid row.
grid-row: 3 / span 2
Justify Self Sets the way a box is justified inside its alignment container along the appropriate axis.
justify-self: start | end | center | stretch
Align SelfOverrides a grid or flex item's align-items value.
align-self: start | end | center | stretch

HOW A GIRD LOOKS LIKE:

11. CSS Content(Dynamic)

COMMANDDESCRIPTIONSYNTAX
CSS VariableUsed in other declarations using the var() function.
 --variable-name: value
Variable UsageUsed in other declarations using the var() function.
var(--variable-name)
Counter ResetCreate a new counter or reversed counter with the given name on the specified element.
counter-reset: name-of-counter
Counter IncrementIncreases or decreases the value of a CSS counter by a given.
counter-increment: name-of-counter
Counter Dynamic ValueAdjust the appearance of content based on its location in a document.
content: counter(name-of-counter)
Attribute Dynamic ValueAdjust the appearance of content based on its location in a document.
content: attr(name-of-attribute)

#css

CSS Cheat Sheet for Beginners and Advanced Users
8.80 GEEK