Skip to content
DevNursery.com - New Web Developer Docs
GitHub

CSS Reference

What is CSS?

CSS (Cascading Style Sheets) is a stylesheet language used for describing the presentation and formatting of web documents written in HTML and XML. It defines how HTML elements should be displayed on the screen, in print, or in other media. CSS allows web developers to control the layout, colors, fonts, and other aspects of web pages.

How CSS Works and Basic Syntax Rules:

  • CSS rules consist of a selector and a set of declarations enclosed in curly braces { }.

  • The selector identifies the HTML element(s) to which the style should be applied.

  • Each declaration consists of a property and a value, separated by a colon :.

  • Declarations are separated by semicolons ;.

  • CSS rules are often placed in a separate stylesheet file (external CSS) or included within the HTML document using the

  • CSS declarations are case-insensitive, but it’s a best practice to use lowercase for property names and values.

CSS Measurements Reference

UnitDescriptionExample Usage
px (Pixels)A fixed unit of measurement that represents one pixel on a screen.font-size: 16px;
emRelative to the font size of the nearest parent element.margin: 1em;
remRelative to the font size of the root (usually the <html> element).font-size: 1rem;
vw (Viewport Width)A percentage of the viewport’s width.width: 50vw;
vh (Viewport Height)A percentage of the viewport’s height.height: 50vh;
vminThe smaller of vw and vh.font-size: 3vmin;
vmaxThe larger of vw and vh.margin: 2vmax;
% (Percentage)Relative to the parent element’s size (e.g., width, height).width: 50%;
cm (Centimeters)A metric unit of measurement (1cm = 10mm).width: 5cm;
mm (Millimeters)A metric unit of measurement (1mm = 1/10th of 1cm).border-width: 2mm;
in (Inches)An imperial unit of measurement (1in = 2.54cm).height: 2in;
pt (Points)Used primarily for print styles (1pt = 1/72 of 1in).font-size: 12pt;
pc (Picas)Another print-specific unit (1pc = 12pt).line-height: 1.5pc;
exRelative to the x-height of the current font.line-height: 2ex;
chRelative to the width of the “0” (zero) character in the current font.width: 20ch;

CSS Properties Reference

TagPurposeExample Usage
colorSets the text color.color: blue;
font-familySpecifies the font family.font-family: Arial, sans-serif;
font-sizeSets the font size.font-size: 16px;
font-weightDefines the font weight (boldness).font-weight: bold;
text-alignAligns text within its container.text-align: center;
text-decorationAdds decorations to text (e.g., underline).text-decoration: underline;
background-colorSets the background color of an element.background-color: #f0f0f0;
marginControls the space outside an element.margin: 10px;
paddingDefines the space inside an element.padding: 5px;
borderCreates a border around an element.border: 1px solid #000;
widthSets the width of an element.width: 200px;
heightDefines the height of an element.height: 100px;
displaySpecifies how an element is displayed.display: block;
floatAligns an element to the left or right.float: left;
positionDetermines the positioning method.position: relative;
topSets the top position of an element.top: 10px;
leftSets the left position of an element.left: 20px;
z-indexControls the stacking order of elements.z-index: 1;
opacityAdjusts the transparency of an element.opacity: 0.5;
text-transformConverts text to uppercase or lowercase.text-transform: uppercase;
line-heightSets the height of a line of text.line-height: 1.5;
list-styleDefines the style of list markers.list-style: square inside;
text-shadowAdds a shadow to text.text-shadow: 1px 1px 2px #333;
box-shadowAdds a shadow to an element’s box.box-shadow: 2px 2px 5px #888888;
border-radiusRounds the corners of an element.border-radius: 10px;
transitionSpecifies CSS transitions for smooth effects.transition: all 0.3s ease-in-out;
background-imageSets a background image.background-image: url('image.jpg');
background-sizeSpecifies the size of background images.background-size: cover;
background-repeatControls how background images repeat.background-repeat: no-repeat;
background-positionSets the position of background images.background-position: center;
opacityControls the opacity of an element.opacity: 0.7;
transformApplies 2D or 3D transformations to elements.transform: rotate(45deg);
cursorChanges the cursor style on hover.cursor: pointer;
text-overflowSpecifies how text should be displayed when it overflows its container.text-overflow: ellipsis;
overflowDetermines how content overflows its box.overflow: hidden;
white-spaceControls how white space is handled.white-space: nowrap;
box-sizingDefines how the total width and height of an element is calculated.box-sizing: border-box;
border-collapseSpecifies whether table borders should be collapsed.border-collapse: collapse;
border-spacingSets the space between table borders.border-spacing: 5px;
font-styleSpecifies the font style (italic, oblique, normal).font-style: italic;
font-variantDefines variations in font appearance.font-variant: small-caps;
letter-spacingAdjusts the spacing between characters.letter-spacing: 2px;
text-alignAligns text horizontally (left, center, right, justify).text-align: right;
vertical-alignAligns inline elements vertically.vertical-align: middle;
word-spacingSets the space between words in text.word-spacing: 4px;
text-indentSpecifies the indentation of the first line of text.text-indent: 20px;

CSS Selectors Reference

Want to get some practice with selectors, try out the CSS Diner.

SelectorPurposeExample Usage
elementSelects all elements of a specified type.p selects all <p> elements.
#idSelects an element with a specific id attribute.#header selects an element with id="header".
.classSelects elements with a specific class attribute..button selects all elements with class="button".
*Selects all elements.* selects all elements on the page.
selector1, selector2Selects multiple elements.h1, h2 selects all <h1> and <h2> elements.
selector > childSelects a direct child of an element.ul > li selects all <li> elements that are direct children of a <ul>.
ancestor descendantSelects descendants of an ancestor element.ul li selects all <li> elements that are descendants of a <ul>.
selector + siblingSelects an adjacent sibling element.h2 + p selects the <p> element immediately following an <h2>.
:hoverSelects an element when hovered over.a:hover selects all <a> elements when hovered.
:activeSelects an element when activated (e.g., clicked).button:active selects all <button> elements when activated.
:focusSelects an element when it receives focus.input:focus selects all <input> elements when focused.
:first-childSelects the first child of an element.ul li:first-child selects the first <li> element inside a <ul>.
:last-childSelects the last child of an element.ul li:last-child selects the last <li> element inside a <ul>.
:nth-child(n)Selects elements based on their position in a parent.tr:nth-child(odd) selects odd rows in a table.
:nth-of-type(n)Selects elements of a specific type based on their position.p:nth-of-type(2) selects the second <p> element.
:not(selector)Selects elements that do not match a given selector.div:not(.special) selects all <div> elements that do not have class="special".
:first-of-typeSelects the first element of its type within its parent.p:first-of-type selects the first <p> element.
:last-of-typeSelects the last element of its type within its parent.p:last-of-type selects the last <p> element.
:nth-last-child(n)Selects elements based on their position, counting from the end.li:nth-last-child(3) selects the third-to-last <li> element.
:nth-last-of-type(n)Selects elements based on their position, counting from the end.div:nth-last-of-type(2) selects the second-to-last <div> element.
:emptySelects elements that have no children.p:empty selects empty <p> elements.
:checkedSelects checked radio buttons and checkboxes.input[type="radio"]:checked selects checked radio buttons.
:disabledSelects disabled form elements.input:disabled selects disabled input elements.
:enabledSelects enabled form elements.input:enabled selects enabled input elements.
:targetSelects the target element in the URL fragment identifier.#section1:target selects the element with id="section1" when it is the target in the URL.

CSS Flexbox Reference

What is Flexbox?

Flexbox, or “Flexible Box Layout,” is a CSS layout model that simplifies the arrangement and alignment of elements within a container. It’s designed to make it easier to create responsive and dynamic web layouts. Flexbox works by defining a parent-child relationship, allowing you to distribute space and control the positioning of elements within a container along either the horizontal or vertical axis. It’s particularly useful for creating complex layouts, evenly spaced elements, and responsive designs, making it a fundamental tool for web developers.

Important Note --> While both Flexbox and CSS Grid are valuable layout tools in CSS, Flexbox is primarily for one-dimensional layouts, think organizing things in a suitcase, and CSS Grid is designed for two-dimensional layouts and complex grid structures, visualize how to load suitcases on to a plane so that no space is wasted. The choice between them depends on the specific layout requirements of your project. Often, they can be used together to achieve more sophisticated designs. Want to get some practice? Give FlexBox Froggy, or try FlexBox Tower Defense a try and see how many levels you can complete.

In Flexbox layouts, you typically have two axes:

  1. The Main Axis: This is the primary axis along which flex items are laid out. It’s determined by the flex-direction property (e.g., row or column).
  2. The Cross Axis: This is the perpendicular axis to the main axis.
PropertyDescriptionValues/Examples
displayDefines the type of box an element generates, enabling Flex layout for a container.display: flex;
flex-directionSets the direction of the main axis along which flex items are placed.row, row-reverse, column, column-reverse
flex-wrapControls whether flex items wrap onto new lines if they overflow the container.nowrap, wrap, wrap-reverse
flex-flowA shorthand for combining flex-direction and flex-wrap properties.flex-flow: row wrap;
orderDetermines the order in which flex items appear within the container.Integer values (e.g., order: 2;)
flex-growSpecifies how much a flex item can grow relative to other items along the main axis.Numeric value (e.g., flex-grow: 1;)
flex-shrinkDefines how much a flex item can shrink relative to other items along the main axis.Numeric value (e.g., flex-shrink: 0;)
flex-basisEstablishes the initial size of a flex item along the main axis.Length value, percentage, auto (e.g., flex-basis: 200px;)
flexA shorthand property for combining flex-grow, flex-shrink, and flex-basis into one declaration.flex: 1 1 auto;
justify-contentDefines how flex items are distributed along the main axis within the container. More on this here.flex-start, flex-end, center, space-between, space-around, space-evenly
align-itemsSpecifies how flex items are aligned along the cross-axis within the container. More on this hereflex-start, flex-end, center, baseline, stretch
align-selfApplies alignment settings to individual flex items, overriding the align-items value for a specific item. More on this hereflex-start, flex-end, center, baseline, stretch
align-contentControls how rows of flex items are aligned along the cross-axis when there’s extra space in the container (applies to multi-line flex containers). More on this hereflex-start, flex-end, center, space-between, space-around, stretch

Justify Content

Syntax -> justify-content: flex-start;. Defines how flex items are distributed along the main (X) axis within the container.

ValuesDescriptionExample
flex-startAligns flex items at the start of the main axis.Flex Start
flex-endAligns flex items at the end of the main axis.Flex End
centerCenters flex items along the main axis.Center
space-betweenDistributes flex items evenly along the main axis, with the first item at the start and the last item at the end, and equal spacing between the rest.Space Between
space-aroundDistributes flex items evenly along the main axis with equal space around them.Space Around
space-evenlyDistributes flex items evenly along the main axis with equal space between and around them.Space Evenly

Align Items

Syntax -> align-items: flex-start;. Specifies how flex items are aligned along the (Y) cross-axis within the container.

ValuesDescriptionExample
flex-startAligns flex items at the start of the cross-axis.Flex Start
flex-endAligns flex items at the end of the cross-axis.Flex End
centerCenters flex items along the cross-axis.Center
baselineAligns flex items such that their baselines align.Baseline
stretchStretches flex items to fill the container along the cross-axis.Stretch

Align Content

Syntax -> align-content: flex-start;. Controls how rows of flex items are aligned along the cross-axis when there’s extra space in the container (applies to multi-line flex containers).

ValuesDescriptionExample
flex-startAligns rows of flex items at the start of the cross-axis.Flex Start
flex-endAligns rows of flex items at the end of the cross-axis.Flex End
centerCenters rows of flex items along the cross-axis.Center
space-betweenDistributes rows of flex items evenly along the cross-axis, with the first row at the start and the last row at the end.Space Between
space-aroundDistributes rows of flex items evenly along the cross-axis with equal space around them.Space Around
stretchStretches rows of flex items to fill the container along the cross-axis.Stretch

Align Self

Syntax -> align-self: flex-start;. Applies alignment settings to individual flex items, overriding the align-items value for a specific item.

ValuesDescriptionExample
flex-startAligns the individual flex item at the start of the cross-axis.Flex Start
flex-endAligns the individual flex item at the end of the cross-axis.Flex End
centerCenters the individual flex item along the cross-axis.Center
baselineAligns the individual flex item such that its baseline aligns with other items’ baselines.Baseline
stretchStretches the individual flex item to fill the container along the cross-axis.Stretch

CSS Grid Reference

What is Grid?

Grid is a versatile layout system in web design that enables precise control over the placement and alignment of elements within a two-dimensional grid structure. Key concepts include defining grid containers and items, specifying rows and columns, using grid lines for item positioning, controlling gaps between cells, achieving alignment both horizontally and vertically, and supporting responsive design through media queries. CSS Grid simplifies complex layouts, enhances code maintainability, and is ideal for modern web design by providing an intuitive and adaptable approach to designing web page layouts.

Important Note --> While both Flexbox and CSS Grid are valuable layout tools in CSS, Flexbox is primarily for one-dimensional layouts, think organizing things in a suitcase, and CSS Grid is designed for two-dimensional layouts and complex grid structures, visualize how to load suitcases on to a plane so that no space is wasted. The choice between them depends on the specific layout requirements of your project. Often, they can be used together to achieve more sophisticated designs. Looking to practice tryout CSS Grid Garden, or CSS Grid Attack

In CSS Grid, you have two main axes:

  1. The Block Axis: This is the vertical axis that runs from top to bottom by default.
  2. The Inline Axis: This is the horizontal axis that runs from left to right by default.
PropertyDescriptionExampleValid Values
display: grid;Defines a grid container.display: grid;grid, inline-grid
grid-template-columnsDefines column sizes and count.grid-template-columns: 1fr 2fr;Length values (e.g., px, em, rem, %), fr, minmax(), auto, repeat()
grid-template-rowsDefines row sizes and count.grid-template-rows: 100px 200px;Length values (e.g., px, em, rem, %), fr, minmax(), auto, repeat()
grid-gapSets the gap between grid columns and rows.grid-gap: 10px 20px;Length values (e.g., px, em, rem, %), initial, inherit, unset
grid-template-areasDefines named grid areas.See example below here.Strings enclosed in quotes, period (.) to create empty grid cells
grid-templateShorthand for defining columns, rows, and areas.grid-template: 1fr 2fr / 100px 200px;Combination of grid-template-columns, grid-template-rows, and grid-template-areas
grid-column-startSpecifies the starting position of a grid item.grid-column-start: 2;Integer values, span, auto, initial, inherit, unset
grid-column-endSpecifies the ending position of a grid item.grid-column-end: span 3;Integer values, span, auto, initial, inherit, unset
grid-row-startSpecifies the starting position of a grid item.grid-row-start: 1;Integer values, span, auto, initial, inherit, unset
grid-row-endSpecifies the ending position of a grid item.grid-row-end: span 2;Integer values, span, auto, initial, inherit, unset
grid-columnShorthand for grid-column-start and grid-column-end.grid-column: 2 / span 3;Combination of values valid for grid-column-start and grid-column-end
grid-rowShorthand for grid-row-start and grid-row-end.grid-row: 1 / span 2;Combination of values valid for grid-row-start and grid-row-end
justify-itemsAligns grid items horizontally within their cells.justify-items: center;start, end, center, stretch, initial, inherit, unset
align-itemsAligns grid items vertically within their cells.align-items: end;start, end, center, stretch, initial, inherit, unset
place-itemsShorthand for justify-items and align-items.place-items: center end;Combination of values valid for justify-items and align-items
justify-contentAligns grid tracks horizontally within the container.justify-content: space-between;start, end, center, stretch, space-between, space-around, space-evenly, initial, inherit, unset
align-contentAligns grid tracks vertically within the container.align-content: center;start, end, center, stretch, space-between, space-around, space-evenly, initial, inherit, unset
place-contentShorthand for justify-content and align-content.place-content: space-evenly center;Combination of values valid for justify-content and align-content
grid-auto-columnsSpecifies the size of automatically created columns.grid-auto-columns: minmax(100px, auto);Length values (e.g., px, em, rem, %), fr, minmax(), auto, initial, inherit, unset
grid-auto-rowsSpecifies the size of automatically created rows.grid-auto-rows: 200px;Length values (e.g., px, em, rem, %), fr, minmax(), auto, initial, inherit, unset
grid-auto-flowControls how auto-placed items are added to the grid.grid-auto-flow: dense;row, column, dense, initial, inherit, unset
gridShorthand for defining both the grid container and its properties in one declaration.grid: auto / repeat(3, 1fr);Combination of values valid for grid-template-rows, grid-template-columns, and grid-template-areas

Grid Template Area

ValueDescriptionExample
User-defined grid areasDefines the layout of grid items by specifying the arrangement of grid areas using a combination of named areas. Each area is represented by a name, and you can arrange items within those areas.Grid Template Areas
noneNo explicit grid template areas are defined, allowing the grid items to be placed based on other layout properties.None
inheritInherits the grid-template-areas property from the parent element.Inherit
initialSets the grid-template-areas property to its default value.Initial

Grid Auto Flow

Syntax -> grid-auto-flow: row dense; Controls how auto-placed items are added to the grid.

ValueDescriptionExample
rowGrid items are placed in rows, filling each row before moving to the next.Row
columnGrid items are placed in columns, filling each column before moving to the next.Column
row denseGrid items are placed in rows, filling each row before moving to the next, and trying to fill gaps in previous rows.Row Dense
column denseGrid items are placed in columns, filling each column before moving to the next, and trying to fill gaps in previous columns.Column Dense
inheritInherits the grid-auto-flow property from the parent element.Inherit
initialSets the grid-auto-flow property to its default value.Initial

Justify Content

Syntax -> justify-content: space-evenly; Aligns grid tracks horizontally within the container.

ValueDescriptionExample
startAligns grid items at the start of the grid container’s inline axis.Start
endAligns grid items at the end of the grid container’s inline axis.End
centerCenters grid items along the grid container’s inline axis.Center
space-betweenDistributes grid items evenly along the grid container’s inline axis, with the first item at the start and the last item at the end.Space Between
space-aroundDistributes grid items evenly along the grid container’s inline axis with equal space around them.Space Around
space-evenlyDistributes grid items evenly along the grid container’s inline axis with equal space between and around them.Space Evenly
stretchStretches grid items to fill the grid container’s inline axis.Stretch

Align Items

Syntax -> align-items: start; Aligns grid items vertically (Y axis) within their cells.

ValueDescriptionExample
startAligns grid items at the start of the grid container’s block axis.Start
endAligns grid items at the end of the grid container’s block axis.End
centerCenters grid items along the grid container’s block axis.Center
stretchStretches grid items to fill the grid container’s block axis.Stretch
baselineAligns grid items such that their baselines align.Baseline
inheritInherits the align-items property from the parent element.Inherit
initialSets the align-items property to its default value.Initial

Align Content

Syntax -> align-content: start; Aligns grid tracks vertically within the container.

ValueDescriptionExample
startAligns rows of grid items at the start of the grid container’s block axis.Start
endAligns rows of grid items at the end of the grid container’s block axis.End
centerCenters rows of grid items along the grid container’s block axis.Center
space-betweenDistributes rows of grid items evenly along the grid container’s block axis, with the first row at the start and the last row at the end.Space Between
space-aroundDistributes rows of grid items evenly along the grid container’s block axis with equal space around them.Space Around
stretchStretches rows of grid items to fill the grid container’s block axis.Stretch
inheritInherits the align-content property from the parent element.Inherit
initialSets the align-content property to its default value.Initial

Example for grid-template-areas:

<!-- EXAMPLE HTML -->
<div class="container">
  <header>Header</header>
  <main>Main content</main>
  <nav>Nav</nav>
  <footer>Footer</footer>
</div>
/* EXAMPLE CSS */
.container {
    display: grid;
    grid-template-columns: 1fr 2fr 3fr;
    grid-template-rows: 100px 200px 300px;
    grid-gap: 10px;
    grid-template-areas:
        "header header header"
        "nav main main"
        "nav footer footer";
}

header {
    grid-area: header;
}

main {
    grid-area: main;
}

nav {
    grid-area: nav;
}

footer {
    grid-area: footer;
}

CSS Animations

CSS animations allow you to create dynamic and visually appealing effects on web pages without the need for JavaScript. They can be applied to various HTML elements, adding motion and interactivity to your website. Here’s a guide to CSS animations:

Basic CSS Animation Syntax

To create a CSS animation, you’ll need to define the animation using the @keyframes rule and apply it to an element using CSS properties. Here’s the basic syntax:

@keyframes animation-name {
    0% {
        /* Initial styles */
    }
    100% {
        /* Final styles */
    }
}

/* Apply the animation to an element */
.element {
    animation-name: animation-name;
    animation-duration: 3s; /* Duration of the animation */
    animation-timing-function: ease; /* Timing function (e.g., linear, ease-in-out) */
    animation-delay: 1s; /* Delay before starting the animation */
    animation-iteration-count: infinite; /* Number of iterations (or '1' for once) */
    animation-direction: alternate; /* Direction (normal, reverse, alternate, etc.) */
    animation-fill-mode: forwards; /* Animation fill mode (forwards, backwards, both, none) */
}
  • @keyframes animation-name: Defines the animation by specifying keyframes at different percentages (0% to 100%).
  • .element: The HTML element to which the animation is applied.
  • animation-duration: The time taken for the animation to complete.
  • animation-timing-function: The timing function controls the pacing of the animation (e.g., ease, linear, ease-in-out).
  • animation-delay: The delay before the animation starts.
  • animation-iteration-count: Specifies the number of times the animation should repeat (e.g., infinite for continuous).
  • animation-direction: Defines the direction of the animation (e.g., normal, reverse, alternate).
  • animation-fill-mode: Specifies how the styles should be applied before and after the animation (e.g., forwards, backwards).

Keyframes

Keyframes define the animation’s intermediate steps. In the example above, 0% represents the initial state of the element, and 100% represents the final state. You can add more keyframes to create complex animations:

@keyframes bounce {
    0%, 100% {
        transform: translateY(0);
    }
    50% {
        transform: translateY(-20px);
    }
}

CSS Properties for Animations

You can animate various CSS properties, including:

  • transform: For translations, rotations, and scaling.
  • opacity: For fading in and out.
  • width, height: For resizing.
  • color, background-color: For color transitions.
  • margin, padding: For moving elements. And more!

Example: Fading In Element

@keyframes fadeIn {
    0% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}

.fade-in {
    animation-name: fadeIn;
    animation-duration: 1s;
    animation-fill-mode: forwards;
}
<div class="fade-in">Hello, CSS Animation!</div>

Using Animation Libraries

For more complex animations and transitions, consider using CSS animation libraries like Animate.css or GreenSock Animation Platform (GSAP). These libraries provide pre-built animations and tools to make your animations more efficient.

Cross-Browser Compatibility

Be aware that CSS animations are supported in modern browsers. To ensure compatibility, consider using vendor prefixes (-webkit-, -moz-, -o-) for specific properties and testing animations in multiple browsers.

CSS animations are a powerful tool for enhancing the user experience and adding engaging visual effects to your web projects. Experiment with different animations to create stunning web designs.