CSS Programming Documentation
Complete guide to CSS styling from basics to advanced
What is CSS?
CSS (Cascading Style Sheets) is a stylesheet language used to describe the presentation of a document written in HTML or XML. CSS describes how elements should be rendered on screen, on paper, in speech, or on other media. CSS saves a lot of work as it can control the layout of multiple web pages all at once. External stylesheets are stored in CSS files.
CSS is designed primarily to enable the separation of document content from document presentation, including aspects such as layout, colors, and fonts. This separation can improve content accessibility, provide more flexibility and control in the specification of presentation characteristics.
History of CSS
CSS was first proposed by Håkon Wium Lie in 1994. CSS1 became a W3C recommendation in 1996, followed by CSS2 in 1998. CSS3, the latest version, is divided into several modules that are developed independently. CSS3 introduced features like rounded corners, shadows, gradients, transitions, animations, and flexible layouts.
Why Use CSS?
- Separation of Concerns: Separates content (HTML) from presentation (CSS)
- Consistency: Apply the same styles to multiple pages
- Maintainability: Update styles across the entire site by changing one file
- Performance: Faster page loads with cached CSS files
- Accessibility: Better support for assistive technologies
- SEO Benefits: Cleaner HTML helps search engines index content
CSS Versions
CSS has evolved through several versions:
- CSS1: Basic styling capabilities (1996)
- CSS2: Added positioning, z-index, media types (1998)
- CSS3: Modular approach with features like Flexbox, Grid, Transitions, Animations (2001-present)
How CSS Works
CSS works by associating style rules with HTML elements. A style rule consists of a selector that identifies which HTML elements to style, and a declaration block that contains one or more property-value pairs. When a browser loads an HTML document, it also loads any linked CSS files and applies the styles to the matching elements.
Inline, Internal, and External CSS
CSS can be applied to HTML in three ways:
- Inline CSS: Using the style attribute directly on HTML elements
- Internal CSS: Using a <style> element in the HTML head section
- External CSS: Linking to an external .css file using the <link> element
External CSS is the recommended approach for most websites as it separates content from presentation and allows for better maintainability.
Basic CSS Syntax
CSS syntax 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 rules can be stacked together.
CSS comments start with /* and end with */. Comments are used to explain your code and may help when you edit the source code at a later date.
/* CSS Comment */
selector {
property: value;
property: value;
}
/* Example */
p {
color: blue;
font-size: 16px;
}
CSS Selectors
Selectors are patterns used to select and style HTML elements. CSS selectors can find HTML elements based on their element name, id, class, attribute, and more. There are several types of selectors: element selectors, class selectors, ID selectors, universal selectors, group selectors, and combinators.
Understanding selectors is fundamental to writing efficient CSS. More specific selectors override less specific ones due to the cascade.
/* Element selector */
h1 { color: blue; }
/* Class selector */
.highlight { background-color: yellow; }
/* ID selector */
#header { font-size: 24px; }
/* Universal selector */
* { margin: 0; padding: 0; }
/* Group selector */
h1, h2, h3 { font-family: Arial; }
Class and ID Selectors
Class selectors select elements with a specific class attribute. To select elements with a specific class, write a period (.) character, followed by the class name. ID selectors select elements with a specific id attribute. To select an element with a specific id, write a hash (#) character, followed by the id.
Class names can be used by multiple elements, while ID names must be unique within the page. IDs have higher specificity than classes.
/* Class selector */
.container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
}
/* Multiple classes */
.box.highlight {
border: 2px solid red;
}
/* ID selector */
#main-navigation {
background-color: #333;
color: white;
}
Attribute Selectors
Attribute selectors select elements based on the presence or value of a given attribute. You can select elements with a specific attribute, with a specific attribute and value, with an attribute value containing a certain word, starting with a certain value, or ending with a certain value.
Attribute selectors are powerful for styling form elements, links, and other elements with specific attributes.
/* Element with attribute */
input[type] {
border: 1px solid #ccc;
}
/* Element with specific attribute value */
input[type="text"] {
padding: 8px;
}
/* Attribute value contains word */
a[href~="example"] {
color: green;
}
/* Attribute value starts with */
a[href^="https"] {
color: blue;
}
/* Attribute value ends with */
a[href$=".pdf"] {
background: url(pdf-icon.png) no-repeat right;
}
Pseudo-classes
Pseudo-classes define special states of an element. They are used to add special effects to some selectors. Common pseudo-classes include :hover (when mouse over), :active (when clicked), :visited (for visited links), :first-child, :last-child, :nth-child(), and :focus.
Pseudo-classes are preceded by a colon (:). They can be combined with other selectors for more specific targeting.
/* Link states */
a:link { color: blue; }
a:visited { color: purple; }
a:hover { color: red; }
a:active { color: orange; }
/* Form focus */
input:focus {
outline: 2px solid blue;
}
/* First and last child */
li:first-child {
font-weight: bold;
}
li:last-child {
border-bottom: none;
}
/* Nth child */
tr:nth-child(even) {
background-color: #f2f2f2;
}
Pseudo-elements
Pseudo-elements are used to style specific parts of an element. They are preceded by double colons (::). Common pseudo-elements include ::before (insert content before), ::after (insert content after), ::first-line (style first line), and ::first-letter (style first letter).
Pseudo-elements are often used with the content property to add decorative elements or text.
/* Before and after */
.quote::before {
content: """;
font-size: 24px;
color: #666;
}
.quote::after {
content: """;
font-size: 24px;
color: #666;
}
/* First letter */
p::first-letter {
font-size: 28px;
font-weight: bold;
float: left;
margin-right: 4px;
}
/* First line */
p::first-line {
font-weight: bold;
color: #333;
}
Combinators
Combinators explain the relationship between selectors. There are four different combinators in CSS:
- Descendant selector (space): Selects all elements that are descendants of a specified element
- Child selector (>): Selects all elements that are direct children of a specified element
- Adjacent sibling selector (+): Selects all elements that are the immediate siblings of a specified element
- General sibling selector (~): Selects all elements that are siblings of a specified element
/* Descendant selector */
div p {
color: blue;
}
/* Child selector */
div > p {
color: green;
}
/* Adjacent sibling selector */
h1 + p {
font-size: 1.2em;
}
/* General sibling selector */
h1 ~ p {
margin-top: 10px;
}
Color Values
CSS color properties specify the color of text, borders, and other elements. Colors can be specified using color names, HEX values, RGB values, RGBA values (with transparency), HSL values, or HSLA values.
Each color format has its advantages. HEX is widely used and compact. RGB provides more precise control. RGBA adds transparency. HSL is more intuitive for humans to understand and adjust.
/* Color names */
.text-primary { color: blue; }
.text-success { color: green; }
/* HEX values */
.text-primary { color: #007bff; }
.text-success { color: #28a745; }
/* RGB values */
.text-primary { color: rgb(0, 123, 255); }
.text-success { color: rgb(40, 167, 69); }
/* RGBA values (with transparency) */
.text-primary { color: rgba(0, 123, 255, 0.8); }
.text-success { color: rgba(40, 167, 69, 0.8); }
/* HSL values */
.text-primary { color: hsl(211, 100%, 50%); }
.text-success { color: hsl(134, 59%, 41%); }
/* HSLA values (with transparency) */
.text-primary { color: hsla(211, 100%, 50%, 0.8); }
.text-success { color: hsla(134, 59%, 41%, 0.8); }
Background Color
The background-color property sets the background color of an element. This property affects the content area and padding, but not the margin. You can apply background colors to any HTML element.
/* Background color */
body {
background-color: #f8f9fa;
}
.bg-light { background-color: #f8f9fa; }
.bg-dark { background-color: #343a40; }
.bg-primary { background-color: #007bff; }
Background Image
The background-image property sets one or more background images for an element. By default, a background-image is placed at the top-left corner of an element, and repeated both vertically and horizontally.
Background images should be optimized for web use. Consider using responsive images and providing fallback colors for when images fail to load.
/* Background image */
.hero {
background-image: url('hero-bg.jpg');
}
/* Multiple background images */
.layered-bg {
background-image: url('pattern.png'), url('texture.jpg');
}
Background Repeat
The background-repeat property sets if/how a background image will be repeated. Values include repeat (both directions), repeat-x (horizontal), repeat-y (vertical), and no-repeat (don't repeat).
/* Background repeat */
.no-repeat {
background-repeat: no-repeat;
}
.repeat-x {
background-repeat: repeat-x;
}
.repeat-y {
background-repeat: repeat-y;
}
.repeat {
background-repeat: repeat;
}
Background Position
The background-position property sets the starting position of a background image. Values can be keywords (top, bottom, left, right, center), percentages, or length values. You can specify one value (horizontal) or two values (horizontal and vertical).
/* Background position */
.bg-position {
background-position: center center;
}
.bg-position-top-right {
background-position: top right;
}
.bg-position-percentage {
background-position: 50% 50%;
}
.bg-position-length {
background-position: 20px 30px;
}
Background Size
The background-size property specifies the size of the background images. Values include auto (default), cover (scales to cover entire container), contain (scales to fit within container), and specific dimensions.
/* Background size */
.bg-cover {
background-size: cover;
}
.bg-contain {
background-size: contain;
}
.bg-specific {
background-size: 300px 200px;
}
.bg-width-only {
background-size: 100% auto;
}
Background Attachment
The background-attachment property sets whether a background image scrolls with the rest of the page or is fixed. Values include scroll (default) and fixed.
/* Background attachment */
.bg-scroll {
background-attachment: scroll;
}
.bg-fixed {
background-attachment: fixed;
}
Background Shorthand
The background property is a shorthand property for setting all background properties. The order of values is: background-color, background-image, background-repeat, background-attachment, background-position, and background-size.
/* Background shorthand */
.hero {
background: #f8f9fa url('hero-bg.jpg') no-repeat center center/cover;
}
/* Another example */
.card {
background: #fff url('pattern.png') repeat-x top left;
}
Opacity and Transparency
The opacity property sets the opacity level for an element. Values range from 0.0 (fully transparent) to 1.0 (fully opaque). Opacity applies to the entire element, including its content.
For transparency without affecting child elements, use RGBA or HSLA color values instead of opacity.
/* Opacity */
.transparent {
opacity: 0.5;
}
/* RGBA for transparency without affecting children */
.semi-transparent {
background-color: rgba(0, 0, 0, 0.5);
}
Font Family
The font-family property specifies the font for an element. You can specify multiple fonts as a "fallback" system, in case the first font is not available. It's recommended to end with a generic font family (serif, sans-serif, monospace, cursive, fantasy).
Web fonts can be added using @font-face or by linking to Google Fonts or other font services. System font stacks provide fallbacks for better performance.
/* Font family */
body {
font-family: 'Helvetica Neue', Arial, sans-serif;
}
/* Serif font stack */
.article {
font-family: Georgia, 'Times New Roman', serif;
}
/* Monospace font stack */
.code {
font-family: 'Courier New', Courier, monospace;
}
/* Custom font with @font-face */
@font-face {
font-family: 'MyCustomFont';
src: url('myfont.woff2') format('woff2'),
url('myfont.woff') format('woff');
}
Font Size
The font-size property sets the size of the text. Values can be specified in various units: pixels (px), ems (relative to parent font size), rems (relative to root font size), percentages (relative to parent font size), viewport units (vw, vh), or keywords (xx-small, x-small, small, medium, large, x-large, xx-large).
Using relative units like rem is recommended for better accessibility and responsive design.
/* Font size with different units */
.text-small { font-size: 14px; }
.text-medium { font-size: 1rem; }
.text-large { font-size: 1.2rem; }
.text-responsive { font-size: 2vw; }
/* Keywords */
.text-x-small { font-size: x-small; }
.text-small { font-size: small; }
.text-medium { font-size: medium; }
.text-large { font-size: large; }
Font Weight
The font-weight property specifies the weight (or boldness) of the font. Values include normal (default), bold, bolder, lighter, and numeric values (100-900). Numeric values follow the OpenType specification, where 400 is normal and 700 is bold.
/* Font weight */
.text-normal { font-weight: normal; }
.text-bold { font-weight: bold; }
.text-light { font-weight: 300; }
.text-heavy { font-weight: 700; }
.text-bolder { font-weight: bolder; }
Font Style
The font-style property specifies the font style for text. Values include normal (default), italic, and oblique. Italic is typically a slanted version of the font, while oblique is simply a slanted version of the normal font.
/* Font style */
.text-normal { font-style: normal; }
.text-italic { font-style: italic; }
.text-oblique { font-style: oblique; }
Line Height
The line-height property specifies the height of a line box. It can be specified as a unitless number (multiplied by the element's font size), a length, a percentage, or the keyword normal. Unitless values are recommended for better scalability.
Proper line height improves readability. A value between 1.4 and 1.6 is generally recommended for body text.
/* Line height */
.text-readable { line-height: 1.5; }
.text-tight { line-height: 1.2; }
.text-loose { line-height: 1.8; }
.text-px { line-height: 24px; }
.text-percent { line-height: 150%; }
Text Alignment
The text-align property specifies the horizontal alignment of text in an element. Values include left, right, center, justify, and inherit. Justify stretches the lines so that each line has equal width.
/* Text alignment */
.text-left { text-align: left; }
.text-center { text-align: center; }
.text-right { text-align: right; }
.text-justify { text-align: justify; }
Text Decoration
The text-decoration property specifies the decoration added to text. Values include none, underline, overline, line-through, and blink. You can combine multiple values.
/* Text decoration */
.no-underline { text-decoration: none; }
.underline { text-decoration: underline; }
.line-through { text-decoration: line-through; }
.underline-overline { text-decoration: underline overline; }
Text Transform
The text-transform property controls the capitalization of text. Values include none (default), capitalize (first letter of each word), uppercase (all uppercase), and lowercase (all lowercase).
/* Text transform */
.text-capitalize { text-transform: capitalize; }
.text-uppercase { text-transform: uppercase; }
.text-lowercase { text-transform: lowercase; }
Letter Spacing
The letter-spacing property increases or decreases the space between characters. Positive values add space, while negative values remove space.
/* Letter spacing */
.text-spaced { letter-spacing: 2px; }
.text-compressed { letter-spacing: -1px; }
.text-normal { letter-spacing: normal; }
Word Spacing
The word-spacing property increases or decreases the space between words. Positive values add space, while negative values remove space.
/* Word spacing */
.text-spaced { word-spacing: 5px; }
.text-compressed { word-spacing: -2px; }
.text-normal { word-spacing: normal; }
Text Shadow
The text-shadow property adds shadow to text. It can take up to four values: horizontal offset, vertical offset, blur radius, and color. You can add multiple shadows by separating them with commas.
/* Text shadow */
.text-shadow {
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}
/* Multiple shadows */
.multishadow {
text-shadow: 1px 1px 0 #fff, 2px 2px 4px rgba(0, 0, 0, 0.5);
}
/* Outline effect */
.outline-text {
text-shadow: -1px -1px 0 #000, 1px 1px 0 #fff;
}
Web Fonts
The @font-face rule allows you to use custom fonts on your web pages. You need to specify the font family name and the source of the font files in different formats for cross-browser compatibility.
/* Custom font */
@font-face {
font-family: 'MyCustomFont';
src: url('myfont.woff2') format('woff2'),
url('myfont.woff') format('woff'),
url('myfont.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
/* Google Fonts */
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');
body {
font-family: 'Roboto', sans-serif;
}
Understanding the Box Model
The CSS box model is a box that wraps around every HTML element. It consists of: content (the actual content), padding (space around content), border (goes around padding and content), and margin (space outside the border). The box model allows us to add a border around elements, and to define space between elements.
Understanding the box model is crucial for layout and spacing. The box-sizing property can change how the box model is calculated.
Content
The content area is where text, images, and other HTML elements appear. The width and height properties set the dimensions of the content area by default.
Padding
Padding clears an area around the content (inside the border). The padding is affected by the background color of the element. Padding can be set for all sides at once or individually for top, right, bottom, and left.
/* Padding shorthand */
.box {
padding: 20px; /* All sides */
}
/* Individual padding */
.box {
padding-top: 10px;
padding-right: 15px;
padding-bottom: 10px;
padding-left: 15px;
}
/* Shorthand padding (top/bottom, left/right) */
.box {
padding: 10px 15px;
}
/* Shorthand padding (top, right, bottom, left) */
.box {
padding: 10px 15px 20px 25px;
}
Border
The border goes around the padding and content. The border properties allow you to specify the style, width, and color of an element's border. You can style all borders at once or individually for each side.
/* Border shorthand */
.box {
border: 2px solid #333;
}
/* Individual border properties */
.box {
border-style: solid;
border-width: 2px;
border-color: #333;
}
/* Individual sides */
.box {
border-top: 2px solid #333;
border-right: 2px solid #333;
border-bottom: 2px solid #333;
border-left: 2px solid #333;
}
/* Border radius for rounded corners */
.rounded {
border-radius: 10px;
}
/* Individual border radius */
.rounded-top {
border-top-left-radius: 10px;
border-top-right-radius: 10px;
}
Margin
Margin clears an area around an element (outside the border). Margin is transparent. Margin can have negative values, which can cause elements to overlap. Like padding, margin can be set for all sides at once or individually.
/* Margin shorthand */
.box {
margin: 20px; /* All sides */
}
/* Individual margin */
.box {
margin-top: 10px;
margin-right: 15px;
margin-bottom: 10px;
margin-left: 15px;
}
/* Shorthand margin (top/bottom, left/right) */
.box {
margin: 10px 15px;
}
/* Shorthand margin (top, right, bottom, left) */
.box {
margin: 10px 15px 20px 25px;
}
/* Auto margin for centering */
.centered {
margin: 0 auto;
width: 80%;
}
Box Sizing
The box-sizing property defines how the width and height of an element are calculated. The default value is content-box, where width and height only apply to the content area. The border-box value includes padding and border in the element's total width and height.
Using border-box is often preferred for responsive design as it makes calculations more predictable.
/* Box sizing */
.content-box {
box-sizing: content-box;
width: 300px;
padding: 20px;
border: 10px solid #333;
/* Total width = 300 + 20*2 + 10*2 = 360px */
}
.border-box {
box-sizing: border-box;
width: 300px;
padding: 20px;
border: 10px solid #333;
/* Total width = 300px */
}
/* Universal box-sizing for easier calculations */
* {
box-sizing: border-box;
}
Outline
The outline property draws a line around an element, outside the border. Unlike border, outline does not take up space and does not affect the layout of the element. Outline is often used for focus states.
/* Outline */
.focusable:focus {
outline: 2px solid #007bff;
}
/* Outline offset */
.offset-outline {
outline: 2px solid #007bff;
outline-offset: 2px;
}
Box Shadow
The box-shadow property adds one or more shadows to an element. It can take up to six values: horizontal offset, vertical offset, blur radius, spread radius, color, and inset/outset. Multiple shadows can be added by separating them with commas.
/* Box shadow */
.shadow {
box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3);
}
/* Multiple shadows */
.multishadow {
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}
/* Inset shadow (inner shadow) */
.inset-shadow {
box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.3);
}
/* No shadow */
.no-shadow {
box-shadow: none;
}
Position Property
The position property specifies the type of positioning method used for an element. Values include static (default), relative, absolute, fixed, and sticky. Positioned elements can be offset using top, right, bottom, and left properties.
Relative positioning moves element relative to its normal position. Absolute positioning moves element relative to its nearest positioned ancestor. Fixed positioning positions element relative to the viewport.
/* Static positioning (default) */
.static-element {
position: static;
}
/* Relative positioning */
.relative-box {
position: relative;
top: 10px;
left: 20px;
}
/* Absolute positioning */
.absolute-element {
position: absolute;
top: 0;
right: 0;
}
/* Fixed positioning */
.fixed-header {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 1000;
}
/* Sticky positioning */
.sticky-nav {
position: sticky;
top: 0;
}
Top, Right, Bottom, Left Properties
These properties specify the position of positioned elements. They work with position: relative, absolute, fixed, and sticky. Values can be specified in pixels, percentages, ems, or other length units.
/* Positioning properties */
.positioned {
position: absolute;
top: 20px;
right: 30px;
bottom: 40px;
left: 50px;
}
/* Percentage positioning */
.percentage-position {
position: absolute;
top: 10%;
left: 20%;
}
Z-Index
The z-index property specifies the stack order of positioned elements. Elements with a higher z-index appear in front of elements with a lower z-index. Z-index only works on positioned elements (position: relative, absolute, fixed, or sticky).
/* Z-index */
.layer-1 { z-index: 1; }
.layer-2 { z-index: 2; }
.layer-3 { z-index: 3; }
/* Negative z-index */
.behind {
z-index: -1;
}
Overflow
The overflow property specifies what happens if content overflows an element's box. Values include visible (default), hidden, scroll, and auto. The overflow-x and overflow-y properties control overflow in specific directions.
/* Overflow */
.overflow-visible {
overflow: visible;
}
.overflow-hidden {
overflow: hidden;
}
.overflow-scroll {
overflow: scroll;
}
.overflow-auto {
overflow: auto;
}
/* Direction-specific overflow */
.overflow-x-hidden {
overflow-x: hidden;
overflow-y: visible;
}
Visibility
The visibility property specifies whether or not an element is visible. Values include visible (default) and hidden. Unlike display: none, hidden elements still take up space in the layout.
/* Visibility */
.visible {
visibility: visible;
}
.hidden {
visibility: hidden;
}
/* Toggle visibility */
.toggle-visibility:hover {
visibility: hidden;
}
Display Property
The display property specifies the display behavior of an element. Common values include block, inline, inline-block, none, flex, grid, and inherit. Block elements take up the full width available and start on a new line. Inline elements only take up as much width as necessary.
inline-block combines properties of both inline and block elements. flex and grid create flexible and grid layouts respectively.
/* Display values */
.block {
display: block;
}
.inline {
display: inline;
}
.inline-block {
display: inline-block;
padding: 10px 20px;
}
.none {
display: none;
}
/* Flex container */
.flex-container {
display: flex;
}
/* Grid container */
.grid-container {
display: grid;
}
Float
The float property specifies whether an element should float to the left or right of its container, allowing text and inline elements to wrap around it. Values include left, right, none, and inherit.
Floats were commonly used for layout before Flexbox and Grid, but are now primarily used for wrapping text around images.
/* Float */
.float-left {
float: left;
margin-right: 15px;
}
.float-right {
float: right;
margin-left: 15px;
}
/* Clear float */
.clearfix::after {
content: "";
display: table;
clear: both;
}
.clear-left {
clear: left;
}
.clear-right {
clear: right;
}
.clear-both {
clear: both;
}
Clear
The clear property specifies which sides of an element's box other floating elements are not allowed. Values include left, right, both, none, and inherit.
/* Clear */
.clear-left {
clear: left;
}
.clear-right {
clear: right;
}
.clear-both {
clear: both;
}
Width and Height
The width and height properties set the width and height of an element. Values can be specified in pixels, percentages, ems, or other length units. Max-width and max-height set the maximum dimensions, while min-width and min-height set the minimum dimensions.
/* Width and height */
.box {
width: 300px;
height: 200px;
}
/* Percentage dimensions */
.responsive {
width: 100%;
height: auto;
}
/* Maximum dimensions */
.max-size {
max-width: 100%;
max-height: 500px;
}
/* Minimum dimensions */
.min-size {
min-width: 300px;
min-height: 200px;
}
Introduction to Flexbox
Flexbox is a one-dimensional layout method for arranging items in rows or columns. Items flex to fill additional space or shrink to fit into smaller spaces. The main concepts are flex container (parent) and flex items (children).
Flexbox provides powerful alignment capabilities and makes it easier to create responsive layouts without using floats or positioning.
Flex Container
To create a flex container, set the display property of an element to flex or inline-flex. This turns the direct children into flex items.
/* Flex container */
.flex-container {
display: flex;
}
/* Inline flex container */
.inline-flex-container {
display: inline-flex;
}
Flex Direction
The flex-direction property sets the direction of flex items in the flex container. Values include row (default, horizontal), row-reverse (horizontal, reversed), column (vertical), and column-reverse (vertical, reversed).
/* Flex direction */
.flex-row {
display: flex;
flex-direction: row;
}
.flex-row-reverse {
display: flex;
flex-direction: row-reverse;
}
.flex-column {
display: flex;
flex-direction: column;
}
.flex-column-reverse {
display: flex;
flex-direction: column-reverse;
}
Flex Wrap
The flex-wrap property specifies whether flex items should wrap or not if there isn't enough space for them on one flex line. Values include nowrap (default, no wrapping), wrap (wrapping), and wrap-reverse (wrapping in reverse order).
/* Flex wrap */
.flex-nowrap {
display: flex;
flex-wrap: nowrap;
}
.flex-wrap {
display: flex;
flex-wrap: wrap;
}
.flex-wrap-reverse {
display: flex;
flex-wrap: wrap-reverse;
}
Justify Content
The justify-content property aligns flex items along the main axis of the flex container. Values include flex-start (default), flex-end, center, space-between, space-around, and space-evenly.
/* Justify content */
.flex-start {
display: flex;
justify-content: flex-start;
}
.flex-end {
display: flex;
justify-content: flex-end;
}
.flex-center {
display: flex;
justify-content: center;
}
.flex-between {
display: flex;
justify-content: space-between;
}
.flex-around {
display: flex;
justify-content: space-around;
}
.flex-evenly {
display: flex;
justify-content: space-evenly;
}
Align Items
The align-items property aligns flex items along the cross axis of the flex container. Values include stretch (default), flex-start, flex-end, center, and baseline.
/* Align items */
.flex-stretch {
display: flex;
align-items: stretch;
}
.flex-start {
display: flex;
align-items: flex-start;
}
.flex-end {
display: flex;
align-items: flex-end;
}
.flex-center {
display: flex;
align-items: center;
}
.flex-baseline {
display: flex;
align-items: baseline;
}
Align Content
The align-content property aligns the flex container's lines when there is extra space in the cross axis. This is similar to align-items but applies to the entire flex container as a whole.
/* Align content */
.flex-content-stretch {
display: flex;
align-content: stretch;
flex-wrap: wrap;
}
.flex-content-start {
display: flex;
align-content: flex-start;
flex-wrap: wrap;
}
.flex-content-end {
display: flex;
align-content: flex-end;
flex-wrap: wrap;
}
.flex-content-center {
display: flex;
align-content: center;
flex-wrap: wrap;
}
Gap
The gap property sets the size of the gap between rows and columns in flex and grid layouts. It's a shorthand for row-gap and column-gap. Gap is a more modern and convenient way to add spacing between flex items.
/* Gap */
.flex-gap {
display: flex;
gap: 20px; /* Same as row-gap: 20px; column-gap: 20px; */
}
/* Different row and column gaps */
.flex-different-gap {
display: flex;
row-gap: 10px;
column-gap: 20px;
}
Flex Grow
The flex-grow property specifies how much a flex item will grow relative to the rest of the flex items in the flex container. The default value is 0, meaning the item won't grow if there's extra space available.
/* Flex grow */
.flex-item-1 {
flex-grow: 1;
}
.flex-item-2 {
flex-grow: 2;
}
/* Shorthand with flex-basis */
.flex-item {
flex: 1 0 auto; /* flex-grow, flex-shrink, flex-basis */
}
Flex Shrink
The flex-shrink property specifies how much a flex item will shrink relative to the rest of the flex items in the flex container. The default value is 1, meaning the item can shrink if necessary.
/* Flex shrink */
.no-shrink {
flex-shrink: 0;
}
.normal-shrink {
flex-shrink: 1;
}
/* Shorthand with flex-basis */
.flex-item {
flex: 0 1 auto; /* flex-grow, flex-shrink, flex-basis */
}
Flex Basis
The flex-basis property specifies the initial size of a flex item before the remaining space is distributed. It can be a length (like 20px, 10em, etc.) or a keyword like auto.
/* Flex basis */
.flex-item {
flex-basis: 200px;
}
.flex-item-auto {
flex-basis: auto;
}
/* Shorthand with flex-grow and flex-shrink */
.flex-item {
flex: 1 1 200px; /* flex-grow, flex-shrink, flex-basis */
}
Align Self
The align-self property allows the default alignment (specified by align-items) to be overridden for individual flex items. Values include auto, flex-start, flex-end, center, baseline, and stretch.
/* Align self */
.flex-item {
align-self: flex-end;
}
.flex-item-center {
align-self: center;
}
.flex-item-stretch {
align-self: stretch;
}
Order
The order property controls the order in which flex items appear in the flex container, regardless of their order in the HTML source. This is useful for responsive design when you want to reorder elements without changing the HTML.
/* Order */
.flex-item-1 {
order: 2; /* Appears second */
}
.flex-item-2 {
order: 1; /* Appears first */
}
.flex-item-3 {
order: 3; /* Appears third */
}
Introduction to CSS Grid
CSS Grid Layout is a two-dimensional layout system for the web. It lets you layout content in rows and columns, and has many features that make building complex layouts straightforward. Grid consists of grid container and grid items.
Grid provides more control than Flexbox for two-dimensional layouts, making it ideal for overall page structure while Flexbox is better for one-dimensional content.
Grid Container
To create a grid container, set the display property of an element to grid or inline-grid. This turns the direct children into grid items.
/* Grid container */
.grid-container {
display: grid;
}
/* Inline grid container */
.inline-grid-container {
display: inline-grid;
}
Grid Template Columns
The grid-template-columns property defines the columns of the grid with a space-separated list of values. Values can be lengths, percentages, or the fr unit (fractional unit).
/* Grid template columns */
.grid-columns {
display: grid;
grid-template-columns: 100px 200px 100px;
}
/* Using fr units */
.grid-fr {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
}
/* Repeat function */
.grid-repeat {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
/* Auto-fit and minmax */
.grid-responsive {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}
Grid Template Rows
The grid-template-rows property defines the rows of the grid with a space-separated list of values. Values can be lengths, percentages, or the fr unit.
/* Grid template rows */
.grid-rows {
display: grid;
grid-template-rows: 100px 200px 100px;
}
/* Using fr units */
.grid-rows-fr {
display: grid;
grid-template-rows: 1fr 2fr 1fr;
}
/* Auto rows */
.grid-auto-rows {
display: grid;
grid-template-rows: 100px auto;
}
Gap
The gap property sets the size of the gap between rows and columns in grid layouts. It's a shorthand for row-gap and column-gap.
/* Gap */
.grid-gap {
display: grid;
gap: 20px; /* Same as row-gap: 20px; column-gap: 20px; */
}
/* Different row and column gaps */
.grid-different-gap {
display: grid;
row-gap: 10px;
column-gap: 20px;
}
Grid Areas
The grid-template-areas property specifies named grid areas, which can be used to position grid items. Each string in the list represents a row, and each word represents a cell.
/* Grid template areas */
.grid-areas {
display: grid;
grid-template-areas:
"header header header"
"sidebar main aside"
"footer footer footer";
grid-template-columns: 200px 1fr 200px;
grid-template-rows: auto 1fr auto;
gap: 20px;
}
/* Grid items */
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.aside { grid-area: aside; }
.footer { grid-area: footer; }
Grid Column and Row
The grid-column and grid-row properties specify the size and location of a grid item. They are shorthand for grid-column-start, grid-column-end, grid-row-start, and grid-row-end.
/* Grid column and row */
.item-1 {
grid-column: 1 / 3; /* From column 1 to 3 */
grid-row: 1; /* Row 1 */
}
.item-2 {
grid-column: 2 / 4; /* From column 2 to 4 */
grid-row: 2 / 4; /* From row 2 to 4 */
}
/* Span multiple columns */
.item-wide {
grid-column: span 2; /* Span 2 columns */
}
/* Span multiple rows */
.item-tall {
grid-row: span 2; /* Span 2 rows */
}
Justify Items
The justify-items property aligns grid items along the inline (row) axis within the grid container. Values include start, end, center, stretch, and space-around.
/* Justify items */
.grid-start {
display: grid;
justify-items: start;
}
.grid-end {
display: grid;
justify-items: end;
}
.grid-center {
display: grid;
justify-items: center;
}
.grid-stretch {
display: grid;
justify-items: stretch;
}
Align Items
The align-items property aligns grid items along the block (column) axis within the grid container. Values include start, end, center, and stretch.
/* Align items */
.grid-start {
display: grid;
align-items: start;
}
.grid-end {
display: grid;
align-items: end;
}
.grid-center {
display: grid;
align-items: center;
}
.grid-stretch {
display: grid;
align-items: stretch;
}
Justify Content
The justify-content property aligns the grid itself within the grid container along the inline (row) axis. This is useful when the grid is smaller than its container.
/* Justify content */
.grid-justify-center {
display: grid;
justify-content: center;
}
.grid-justify-end {
display: grid;
justify-content: end;
}
.grid-justify-space-between {
display: grid;
justify-content: space-between;
}
.grid-justify-space-around {
display: grid;
justify-content: space-around;
}
.grid-justify-space-evenly {
display: grid;
justify-content: space-evenly;
}
Align Content
The align-content property aligns the grid itself within the grid container along the block (column) axis. This is useful when the grid is smaller than its container.
/* Align content */
.grid-align-center {
display: grid;
align-content: center;
}
.grid-align-end {
display: grid;
align-content: end;
}
.grid-align-stretch {
display: grid;
align-content: stretch;
}
Place Items
The place-items property is a shorthand for align-items and justify-items. It aligns grid items both horizontally and vertically.
/* Place items */
.grid-center {
display: grid;
place-items: center; /* Same as align-items: center; justify-items: center; */
}
.grid-end {
display: grid;
place-items: end end; /* Same as align-items: end; justify-items: end; */
}
.grid-stretch {
display: grid;
place-items: stretch stretch; /* Same as align-items: stretch; justify-items: stretch; */
}
Grid Auto Flow
The grid-auto-flow property controls how auto-placed items are placed in the grid. It's a shorthand for grid-auto-flow-row, grid-auto-flow-column, grid-auto-flow-dense, grid-auto-flow-row-dense, and grid-auto-flow-column-dense.
/* Grid auto flow */
.grid-row {
display: grid;
grid-auto-flow: row; /* Default */
}
.grid-column {
display: grid;
grid-auto-flow: column;
}
.grid-dense {
display: grid;
grid-auto-flow: dense;
}
Grid Auto Columns
The grid-auto-columns property specifies the size of the columns in an implicit grid. This is useful when you want columns to be automatically created based on content.
/* Grid auto columns */
.grid-auto-columns {
display: grid;
grid-template-columns: 200px; /* First column is 200px */
grid-auto-columns: 1fr 1fr; /* Subsequent columns are equal fractions */
}
/* Using minmax */
.grid-responsive {
display: grid;
grid-template-columns: 200px;
grid-auto-columns: minmax(100px, 1fr);
}
Grid Auto Rows
The grid-auto-rows property specifies the size of the rows in an implicit grid. This is useful when you want rows to be automatically created based on content.
/* Grid auto rows */
.grid-auto-rows {
display: grid;
grid-template-rows: 100px; /* First row is 100px */
grid-auto-rows: 50px; /* Subsequent rows are 50px */
}
/* Using minmax */
.grid-auto-rows {
display: grid;
grid-template-rows: 100px;
grid-auto-rows: minmax(50px, auto);
}
What is Responsive Design?
Responsive design is an approach to web design that makes web pages render well on a variety of devices and window or screen sizes. It uses flexible grids, flexible images, CSS media queries, and other techniques to create adaptive layouts.
The goal is to provide an optimal viewing and interaction experience—easy reading and navigation with a minimum of resizing, panning, and scrolling—across a wide range of devices.
Mobile-First Design
Mobile-first design is an approach where you design for mobile devices first, then progressively enhance the experience for larger screens. This ensures your site works well on small screens and takes advantage of additional space on larger screens.
Mobile-first design often uses min-width media queries rather than max-width, making the base styles mobile-friendly and adding enhancements for larger screens.
/* Mobile-first approach */
.container {
width: 100%;
padding: 0 15px;
}
/* Tablet styles */
@media (min-width: 768px) {
.container {
max-width: 750px;
margin: 0 auto;
}
}
/* Desktop styles */
@media (min-width: 1024px) {
.container {
max-width: 1200px;
}
}
Media Queries
Media queries allow you to apply CSS styles based on device characteristics like screen width, height, orientation, and resolution. They are essential for responsive design, ensuring your website looks good on all devices.
Common breakpoints include mobile (320px-768px), tablet (768px-1024px), and desktop (1024px+). You can use min-width, max-width, orientation, and other features.
/* Mobile styles (default) */
.navigation {
display: flex;
flex-direction: column;
}
/* Tablet styles */
@media (min-width: 768px) {
.navigation {
flex-direction: row;
justify-content: space-between;
}
}
/* Desktop styles */
@media (min-width: 1024px) {
.navigation {
max-width: 1200px;
margin: 0 auto;
}
}
/* Orientation specific */
@media (orientation: landscape) {
.hero {
height: 100vh;
}
}
/* High DPI displays */
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
.logo {
background-image: url('logo@2x.png');
}
}
Responsive Images
Responsive images adapt to different screen sizes and resolutions. Techniques include using max-width: 100%, using srcset and sizes attributes with the <picture> element, and using CSS background-image with media queries.
/* Responsive images */
img {
max-width: 100%;
height: auto;
}
/* Responsive background images */
.hero {
background-image: url('small.jpg');
}
@media (min-width: 768px) {
.hero {
background-image: url('medium.jpg');
}
}
@media (min-width: 1024px) {
.hero {
background-image: url('large.jpg');
}
}
Responsive Typography
Responsive typography adjusts font sizes based on screen size to ensure readability on all devices. Using relative units like rem or vw allows text to scale proportionally.
/* Responsive typography */
html {
font-size: 16px;
}
@media (min-width: 768px) {
html {
font-size: 18px;
}
}
@media (min-width: 1024px) {
html {
font-size: 20px;
}
}
/* Fluid typography */
h1 {
font-size: clamp(1.5rem, 4vw, 2.5rem);
}
Responsive Layouts
Responsive layouts adapt to different screen sizes. Common approaches include using Flexbox or Grid with media queries, using percentage widths, and implementing navigation patterns like hamburger menus for mobile.
/* Responsive grid layout */
.grid {
display: grid;
grid-template-columns: 1fr;
gap: 20px;
}
@media (min-width: 768px) {
.grid {
grid-template-columns: 1fr 1fr;
}
}
@media (min-width: 1024px) {
.grid {
grid-template-columns: 1fr 1fr 1fr;
}
}
/* Responsive flexbox layout */
.flexbox {
display: flex;
flex-direction: column;
}
@media (min-width: 768px) {
.flexbox {
flex-direction: row;
}
}
Viewport Units
Viewport units are relative to the viewport size: vw (1% of viewport width), vh (1% of viewport height), vmin (smaller of vw and vh), and vmax (larger of vw and vh). They are useful for creating truly responsive designs.
/* Viewport units */
.full-width {
width: 100vw;
}
.full-height {
height: 100vh;
}
/* Responsive font size */
.responsive-text {
font-size: 2vw;
}
/* Square element */
.square {
width: 50vmin;
height: 50vmin;
}
Container Queries
Container Queries (a newer CSS feature) allow you to apply styles based on the size of a container rather than the viewport. This is useful for components that need to adapt based on their available space rather than the screen size.
/* Container queries */
@container (min-width: 700px) {
.card {
display: grid;
grid-template-columns: 1fr 1fr;
}
}
@container (min-width: 1024px) {
.card {
grid-template-columns: 1fr 1fr 1fr;
}
}
Responsive Images with srcset and sizes
The srcset and sizes attributes on <img> elements allow the browser to choose the most appropriate image based on screen size and resolution. This improves performance by serving smaller images to smaller devices.
<img src="image-small.jpg"
srcset="image-medium.jpg 768w, image-large.jpg 1024w"
sizes="(max-width: 767px) 100vw, (max-width: 1023px) 50vw, 33vw"
alt="Responsive image">
Modern CSS Features for Responsive Design
Modern CSS features like CSS Grid, Flexbox, Custom Properties, and Container Queries make responsive design easier and more maintainable. These features reduce the need for complex media queries and JavaScript solutions.
/* CSS Custom Properties for responsive design */
:root {
--mobile-padding: 15px;
--tablet-padding: 20px;
--desktop-padding: 30px;
}
.container {
padding: var(--mobile-padding);
}
@media (min-width: 768px) {
.container {
padding: var(--tablet-padding);
}
}
@media (min-width: 1024px) {
.container {
padding: var(--desktop-padding);
}
}
Project Overview
For the final project, you'll create a comprehensive responsive website that demonstrates all the CSS concepts learned throughout the course. This project will include responsive design, modern layout techniques, animations, and a polished user interface.
Project Structure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Modern Website - CSS Project</title>
<meta name="description" content="A modern responsive website showcasing CSS techniques">
<link rel="stylesheet" href="styles.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap">
</head>
<body>
<header class="header">
<nav class="navbar">
<div class="nav-container">
<a href="#" class="logo">Modern Website</a>
<ul class="nav-menu">
<li><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#portfolio">Portfolio</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
<button class="menu-toggle" aria-label="Toggle navigation">
<span></span>
<span></span>
<span></span>
</button>
</div>
</nav>
</header>
<main>
<section id="hero" class="hero">
<div class="hero-content">
<h1>Welcome to Our Modern Website</h1>
<p>We create beautiful, responsive websites with modern CSS techniques</p>
<a href="#portfolio" class="btn btn-primary">View Our Work</a>
<a href="#contact" class="btn btn-outline">Contact Us</a>
</div>
<div class="hero-image">
<div class="hero-shape"></div>
</div>
</section>
<section id="about" class="section">
<div class="container">
<h2>About Us</h2>
<div class="about-content">
<div class="about-text">
<p>We are a team of creative developers passionate about building modern, responsive websites. With expertise in HTML, CSS, and JavaScript, we create digital experiences that look great and work flawlessly across all devices.</p>
<p>Our approach combines clean code with beautiful design to deliver websites that not only look good but also provide excellent user experiences.</p>
<a href="#team" class="btn">Meet Our Team</a>
</div>
<div class="about-image">
<div class="about-shape"></div>
</div>
</div>
</div>
</section>
<section id="services" class="section bg-light">
<div class="container">
<h2>Our Services</h2>
<div class="services-grid">
<div class="service-card">
<div class="service-icon">
<i class="fas fa-code"></i>
</div>
<h3>Web Development</h3>
<p>Custom websites built with modern technologies and best practices.</p>
</div>
<div class="service-card">
<div class="service-icon">
<i class="fas fa-mobile-alt"></i>
</div>
<h3>Responsive Design</h3>
<p>Websites that adapt seamlessly to different screen sizes and devices.</p>
</div>
<div class="service-card">
<div class="service-icon">
<i class="fas fa-palette"></i>
</div>
<h3>UI/UX Design</h3>
<p>Beautiful interfaces that are intuitive and user-friendly.</p>
</div>
<div class="service-card">
<div class="service-icon">
<i class="fas fa-rocket"></i>
</div>
<h3>Performance Optimization</h3>
<p>Fast-loading websites optimized for speed and SEO.</p>
</div>
</div>
</div>
</section>
<section id="portfolio" class="section">
<div class="container">
<h2>Our Portfolio</h2>
<div class="filter-buttons">
<button class="filter-btn active" data-filter="all">All</button>
<button class="filter-btn" data-filter="web">Web Design</button>
<button class="filter-btn" data-filter="mobile">Mobile Apps</button>
<button class="filter-btn" data-filter="ui">UI/UX</button>
</div>
<div class="portfolio-grid">
<div class="portfolio-item" data-category="web">
<div class="portfolio-image">
<img src="images/project1.jpg" alt="Project 1" width="400" height="300">
</div>
<div class="portfolio-content">
<h3>E-commerce Website</h3>
<p>A fully functional e-commerce website with shopping cart and payment integration.</p>
<div class="portfolio-tags">
<span>HTML</span>
<span>CSS</span>
<span>JavaScript</span>
</div>
<div class="portfolio-links">
<a href="#"><i class="fas fa-eye"></i></a>
<a href="#"><i class="fas fa-link"></i></a>
</div>
</div>
</div>
<!-- More portfolio items -->
</div>
</div>
</section>
<section id="team" class="section bg-light">
<div class="container">
<h2>Our Team</h2>
<div class="team-grid">
<div class="team-member">
<div class="team-image">
<img src="images/team1.jpg" alt="Team Member 1" width="300" height="300">
</div>
<div class="team-content">
<h3>John Doe</h3>
<p>Frontend Developer</p>
<div class="team-social">
<a href="#"><i class="fab fa-linkedin"></i></a>
<a href="#"><i class="fab fa-github"></i></a>
<a href="#"><i class="fab fa-twitter"></i></a>
</div>
</div>
<!-- More team members -->
</div>
</div>
</section>
<section id="testimonials" class="section">
<div class="container">
<h2>What Our Clients Say</h2>
<div class="testimonials-slider">
<div class="testimonial">
<div class="testimonial-content">
<p>"Working with this team was a great experience. They delivered our project on time and exceeded our expectations."</p>
</div>
<div class="testimonial-author">
<div class="author-image">
<img src="images/author1.jpg" alt="Author 1" width="60" height="60">
</div>
<div class="author-info">
<h4>Jane Smith</h4>
<p>CEO, Tech Company</p>
</div>
</div>
</div>
<!-- More testimonials -->
</div>
</div>
</section>
<section id="contact" class="section bg-light">
<div class="container">
<h2>Contact Us</h2>
<div class="contact-content">
<div class="contact-info">
<h3>Get In Touch</h3>
<p>We'd love to hear from you about your project. Send us a message and we'll respond as soon as possible.</p>
<div class="contact-details">
<div class="contact-item">
<i class="fas fa-envelope"></i>
<span>info@example.com</span>
</div>
<div class="contact-item">
<i class="fas fa-phone"></i>
<span>+1 (123) 456-7890</span>
</div>
<div class="contact-item">
<i class="fas fa-map-marker-alt"></i>
<span>123 Main St, City, State 12345</span>
</div>
</div>
<div class="social-links">
<a href="#"><i class="fab fa-facebook-f"></i></a>
<a href="#"><i class="fab fa-twitter"></i></a>
<a href="#"><i class="fab fa-instagram"></i></a>
<a href="#"><i class="fab fa-linkedin"></i></a>
</div>
</div>
<div class="contact-form">
<form action="#" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input type="text" id="subject" name="subject" required>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea id="message" name="message" rows="5" required></textarea>
</div>
<button type="submit" class="btn">Send Message</button>
</form>
</div>
</div>
</div>
</section>
</main>
<footer class="footer">
<div class="container">
<div class="footer-content">
<div class="footer-logo">
<a href="#">Modern Website</a>
</div>
<div class="footer-links">
<ul>
<li><a href="#">Privacy Policy</a></li>
<li><a href="#">Terms of Service</a></li>
<li><a href="#">Sitemap</a></li>
</ul>
</div>
<div class="footer-social">
<a href="#"><i class="fab fa-facebook-f"></i></a>
<a href="#"><i class="fab fa-twitter"></i></a>
<a href="#"><i class="fab fa-instagram"></i></a>
<a href="#"><i class="fab fa-linkedin"></i></a>
</div>
<div class="footer-copyright">
<p>© 2023 Modern Website. All rights reserved.</p>
</div>
</div>
</footer>
<script src="script.js"></script>
</body>
</html>
CSS Structure
/* CSS Variables */
:root {
--primary-color: #007bff;
--secondary-color: #6c757d;
--accent-color: #17a2b8;
--light-color: #f8f9fa;
--dark-color: #343a40;
--success-color: #28a745;
--info-color: #17a2b8;
--warning-color: #ffc107;
--danger-color: #dc3545;
--font-family-sans: 'Inter', sans-serif;
--font-family-serif: 'Georgia', serif;
--font-family-mono: 'Courier New', monospace;
--border-radius: 0.375rem;
--box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
--transition: all 0.3s ease;
}
/* Base styles */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: var(--font-family-sans);
line-height: 1.6;
color: var(--dark-color);
background-color: var(--light-color);
}
/* Typography */
h1, h2, h3, h4, h5, h6 {
font-weight: 600;
line-height: 1.2;
margin-bottom: 1rem;
}
p {
margin-bottom: 1rem;
}
/* Buttons */
.btn {
display: inline-block;
font-weight: 500;
text-align: center;
vertical-align: middle;
padding: 0.75rem 1.5rem;
border-radius: var(--border-radius);
transition: var(--transition);
cursor: pointer;
text-decoration: none;
}
.btn-primary {
color: #fff;
background-color: var(--primary-color);
border: 1px solid var(--primary-color);
}
.btn-primary:hover {
background-color: #0069d9;
border-color: #0069d9;
}
.btn-outline {
color: var(--primary-color);
background-color: transparent;
border: 1px solid var(--primary-color);
}
.btn-outline:hover {
color: #fff;
background-color: var(--primary-color);
}
/* Cards */
.card {
background: #fff;
border-radius: var(--border-radius);
box-shadow: var(--box-shadow);
overflow: hidden;
transition: var(--transition);
}
.card:hover {
transform: translateY(-5px);
box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.15);
}
.card-header {
padding: 1.25rem 1.5rem;
margin-bottom: 0;
background-color: rgba(0, 0, 0, 0.03);
border-bottom: 1px solid rgba(0, 0, 0, 0.125);
}
.card-body {
padding: 1.5rem;
}
/* Forms */
.form-group {
margin-bottom: 1rem;
}
.form-control {
display: block;
width: 100%;
padding: 0.75rem 1rem;
font-size: 1rem;
line-height: 1.5;
color: #495057;
background-color: #fff;
border: 1px solid #ced4da;
border-radius: var(--border-radius);
transition: var(--transition);
}
.form-control:focus {
color: #495057;
background-color: #fff;
border-color: #80bdff;
outline: 0;
box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}
/* Navigation */
.navbar {
padding: 1rem 0;
background-color: var(--dark-color);
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.navbar-brand {
font-weight: 700;
color: #fff;
text-decoration: none;
}
.navbar-nav .nav-link {
color: rgba(255, 255, 255, 0.8);
padding: 0.5rem 1rem;
text-decoration: none;
transition: color 0.2s ease;
}
.navbar-nav .nav-link:hover {
color: #fff;
}
/* Hero Section */
.hero {
padding: 6rem 0;
background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
color: #fff;
text-align: center;
}
.hero-content {
max-width: 800px;
margin: 0 auto;
}
.hero h1 {
font-size: 3.5rem;
font-weight: 700;
margin-bottom: 1.5rem;
}
/* Sections */
.section {
padding: 5rem 0;
}
.section.bg-light {
background-color: var(--light-color);
}
/* Footer */
.footer {
background-color: var(--dark-color);
color: #fff;
padding: 3rem 0;
text-align: center;
}
/* Responsive Design */
@media (max-width: 767.98px) {
.navbar-nav {
display: none;
}
.menu-toggle {
display: block;
}
.nav-menu {
display: none;
position: absolute;
top: 100%;
left: 0;
width: 100%;
background-color: var(--dark-color);
flex-direction: column;
padding: 1rem 0;
text-align: center;
}
.nav-menu.active {
display: flex;
}
.hero {
padding: 4rem 0;
}
.hero h1 {
font-size: 2.5rem;
}
}
@media (min-width: 768px) {
.navbar-nav {
display: flex;
}
.menu-toggle {
display: none;
}
.nav-menu {
display: flex;
position: static;
background-color: transparent;
padding: 0;
text-align: left;
}
.hero {
padding: 6rem 0;
}
.hero h1 {
font-size: 3.5rem;
}
}
Project Features
- Responsive Design: Adapts to different screen sizes using media queries
- Modern Layout: Uses CSS Grid and Flexbox for layout
- Typography: Implements a clear visual hierarchy with proper spacing
- Color Scheme: Uses a consistent color palette with CSS variables
- Components: Reusable components like buttons, cards, and forms
- Animations: Includes hover effects and transitions for interactivity
- Navigation: Responsive navigation with hamburger menu for mobile
- Forms: Styled form elements with proper validation states
Project Extensions
Once you've implemented the basic website, consider these extensions:
- Add a blog section with pagination
- Implement a dark mode toggle
- Add more advanced animations and micro-interactions
- Create a portfolio filter with JavaScript
- Add form validation with JavaScript
- Implement a loading skeleton screen
- Add smooth scrolling and scroll indicators
CSS Transitions
CSS transitions allow you to change property values smoothly over a given duration. They provide a way to control animation speed when changing CSS properties. Instead of having property changes take effect immediately, you can make the property changes take place over a period of time.
Transitions are commonly used for hover effects, focus states, and other interactive elements to provide visual feedback to users.
/* Basic transition */
.button {
background-color: #007bff;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: #0056b3;
}
/* Multiple properties transition */
.card {
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}
/* Transition shorthand */
.link {
color: #007bff;
transition: all 0.2s ease-in-out;
}
.link:hover {
color: #0056b3;
text-decoration: underline;
}
Transition Properties
The transition property is a shorthand for four transition properties:
- transition-property: Specifies the name of the CSS property the transition effect is for
- transition-duration: Specifies how many seconds or milliseconds a transition effect takes to complete
- transition-timing-function: Specifies the speed curve of the transition effect
- transition-delay: Specifies when the transition effect will start
/* Individual transition properties */
.button {
transition-property: background-color;
transition-duration: 0.3s;
transition-timing-function: ease;
transition-delay: 0s;
}
/* Timing functions */
.ease { transition-timing-function: ease; }
.ease-in { transition-timing-function: ease-in; }
.ease-out { transition-timing-function: ease-out; }
.ease-in-out { transition-timing-function: ease-in-out; }
.linear { transition-timing-function: linear; }
/* Custom cubic-bezier timing function */
.custom-timing {
transition-timing-function: cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
CSS Animations
CSS animations make it possible to animate transitions from one CSS style configuration to another. They consist of two components: keyframes that define the stages and styles of the animation, and animation properties that assign the animation to a specific CSS element.
Unlike transitions, animations don't require a triggering event like a hover or focus state. They can run automatically when the page loads or be controlled with JavaScript.
/* Define keyframes */
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes slideIn {
from { transform: translateX(-100%); }
to { transform: translateX(0); }
}
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.1); }
100% { transform: scale(1); }
}
/* Apply animation */
.fade-in-element {
animation: fadeIn 1s ease-in-out;
}
.slide-in-element {
animation: slideIn 0.5s ease-out;
}
.pulse-element {
animation: pulse 2s infinite;
}
Animation Properties
The animation property is a shorthand for eight animation properties:
- animation-name: Specifies the name of the @keyframes animation
- animation-duration: Specifies how many seconds or milliseconds an animation takes to complete
- animation-timing-function: Specifies the speed curve of the animation
- animation-delay: Specifies a delay before the animation will start
- animation-iteration-count: Specifies how many times an animation should be played
- animation-direction: Specifies whether an animation should be played in reverse direction or alternate cycles
- animation-fill-mode: Specifies what values are applied by the animation before and after it is executing
- animation-play-state: Specifies whether the animation is running or paused
/* Animation shorthand */
.element {
animation: slideIn 0.5s ease-out 0s 1 normal forwards running;
}
/* Individual animation properties */
.element {
animation-name: slideIn;
animation-duration: 0.5s;
animation-timing-function: ease-out;
animation-delay: 0s;
animation-iteration-count: 1;
animation-direction: normal;
animation-fill-mode: forwards;
animation-play-state: running;
}
/* Animation iteration count */
.once { animation-iteration-count: 1; }
.twice { animation-iteration-count: 2; }
.infinite { animation-iteration-count: infinite; }
/* Animation direction */
.normal { animation-direction: normal; }
.reverse { animation-direction: reverse; }
.alternate { animation-direction: alternate; }
.alternate-reverse { animation-direction: alternate-reverse; }
/* Animation fill mode */
.none { animation-fill-mode: none; }
.forwards { animation-fill-mode: forwards; }
.backwards { animation-fill-mode: backwards; }
.both { animation-fill-mode: both; }
CSS Transforms
CSS transforms allow you to modify the coordinate space of the CSS visual formatting model. Using transforms, you can move, rotate, scale, and skew elements. Transforms are often used with transitions and animations to create dynamic effects.
/* Transform functions */
.translate { transform: translate(50px, 100px); }
.translateX { transform: translateX(50px); }
.translateY { transform: translateY(100px); }
.scale { transform: scale(1.5); }
.scaleX { transform: scaleX(1.5); }
.scaleY { transform: scaleY(1.5); }
.rotate { transform: rotate(45deg); }
.rotateX { transform: rotateX(45deg); }
.rotateY { transform: rotateY(45deg); }
.skew { transform: skew(10deg, 20deg); }
.skewX { transform: skewX(10deg); }
.skewY { transform: skewY(20deg); }
/* Multiple transforms */
.combined {
transform: translate(50px, 100px) rotate(45deg) scale(1.5);
}
/* Transform origin */
.origin-center { transform-origin: center; }
.origin-top-left { transform-origin: top left; }
.origin-bottom-right { transform-origin: bottom right; }
3D Transforms
CSS also supports 3D transforms, which allow you to manipulate elements in three-dimensional space. 3D transforms require setting a perspective on a parent element to create the 3D effect.
/* 3D transforms */
.rotate3d { transform: rotate3d(1, 1, 1, 45deg); }
.rotateX3d { transform: rotateX(45deg); }
.rotateY3d { transform: rotateY(45deg); }
.rotateZ3d { transform: rotateZ(45deg); }
.translate3d { transform: translate3d(50px, 100px, 200px); }
.translateZ { transform: translateZ(200px); }
.scale3d { transform: scale3d(1.5, 1.2, 0.8); }
.scaleZ { transform: scaleZ(0.8); }
/* Perspective for 3D transforms */
.container-3d {
perspective: 1000px;
}
/* Transform style for 3D */
.preserve-3d {
transform-style: preserve-3d;
}
/* Backface visibility */
.backface-visible { backface-visibility: visible; }
.backface-hidden { backface-visibility: hidden; }
Filter Effects
CSS filters allow you to apply graphical effects like blurring, sharpening, or color shifting to elements. Filters are commonly used for adjusting the rendering of images, backgrounds, and borders.
/* Filter functions */
.blur { filter: blur(5px); }
.brightness { filter: brightness(150%); }
.contrast { filter: contrast(200%); }
.grayscale { filter: grayscale(100%); }
.hue-rotate { filter: hue-rotate(90deg); }
.invert { filter: invert(100%); }
.opacity { filter: opacity(50%); }
.saturate { filter: saturate(200%); }
.sepia { filter: sepia(100%); }
/* Multiple filters */
.combined-filters {
filter: contrast(200%) brightness(150%);
}
/* Drop shadow filter */
.drop-shadow {
filter: drop-shadow(5px 5px 10px rgba(0, 0, 0, 0.5));
}
Backdrop Filter
The backdrop-filter property allows you to apply graphical effects to the area behind an element. This is commonly used for creating frosted glass effects.
/* Backdrop filter for frosted glass effect */
.frosted-glass {
background-color: rgba(255, 255, 255, 0.3);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px); /* For Safari */
}
/* Other backdrop filter effects */
.backdrop-grayscale {
backdrop-filter: grayscale(100%);
}
.backdrop-brightness {
backdrop-filter: brightness(150%);
}
.backdrop-contrast {
backdrop-filter: contrast(200%);
}
Clip Path
The clip-path property creates a clipping region that defines what part of an element should be displayed. This allows you to create complex shapes and effects.
/* Basic clip paths */
.circle { clip-path: circle(50%); }
.ellipse { clip-path: ellipse(50% 40% at 50% 50%); }
.polygon { clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%); }
/* Custom polygon */
.triangle {
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
}
.hexagon {
clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
}
/* Using clip-path with animation */
.animated-clip {
animation: morphShape 5s infinite alternate;
}
@keyframes morphShape {
0% { clip-path: circle(50% at 50% 50%); }
100% { clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%); }
}
Other Common Properties
Here are some other useful CSS properties for creating effects:
/* Cursor property */
.pointer { cursor: pointer; }
.not-allowed { cursor: not-allowed; }
.help { cursor: help; }
.crosshair { cursor: crosshair; }
.move { cursor: move; }
.text { cursor: text; }
.wait { cursor: wait; }
.grab { cursor: grab; }
.grabbing { cursor: grabbing; }
/* User select property */
.select-none { user-select: none; }
.select-text { user-select: text; }
.select-all { user-select: all; }
.select-auto { user-select: auto; }
/* Pointer events property */
.pointer-events-none { pointer-events: none; }
.pointer-events-auto { pointer-events: auto; }
/* Object fit property for images and videos */
.object-fit-contain { object-fit: contain; }
.object-fit-cover { object-fit: cover; }
.object-fit-fill { object-fit: fill; }
.object-fit-none { object-fit: none; }
.object-fit-scale-down { object-fit: scale-down; }
/* Will change property for performance optimization */
.will-change-transform { will-change: transform; }
.will-change-opacity { will-change: opacity; }
.will-change-scroll-position { will-change: scroll-position; }
/* Mix blend mode */
.blend-multiply { mix-blend-mode: multiply; }
.blend-screen { mix-blend-mode: screen; }
.blend-overlay { mix-blend-mode: overlay; }
.blend-darken { mix-blend-mode: darken; }
.blend-lighten { mix-blend-mode: lighten; }
.blend-color-dodge { mix-blend-mode: color-dodge; }
.blend-color-burn { mix-blend-mode: color-burn; }
.blend-hard-light { mix-blend-mode: hard-light; }
.blend-soft-light { mix-blend-mode: soft-light; }
.blend-difference { mix-blend-mode: difference; }
.blend-exclusion { mix-blend-mode: exclusion; }
.blend-hue { mix-blend-mode: hue; }
.blend-saturation { mix-blend-mode: saturation; }
.blend-color { mix-blend-mode: color; }
.blend-luminosity { mix-blend-mode: luminosity; }
/* Isolation property */
.isolate { isolation: isolate; }
/* Scroll snap type */
.scroll-snap-x { scroll-snap-type: x mandatory; }
.scroll-snap-y { scroll-snap-type: y mandatory; }
.scroll-snap-both { scroll-snap-type: both mandatory; }
/* Scroll snap align */
.snap-start { scroll-snap-align: start; }
.snap-center { scroll-snap-align: center; }
.snap-end { scroll-snap-align: end; }
Animation Performance Tips
When working with animations, it's important to consider performance:
- Use transform and opacity: These properties are the most performant as they can be handled by the GPU
- Avoid animating layout properties: Properties like width, height, margin, and padding trigger layout recalculation
- Use will-change: Hint to the browser which properties will change to optimize rendering
- Limit the number of animated elements: Too many simultaneous animations can impact performance
- Use requestAnimationFrame: For JavaScript animations, use requestAnimationFrame for smoother performance
/* Good performance animation */
.performant-animation {
transform: translateX(100px);
opacity: 0.5;
will-change: transform, opacity;
}
/* Less performant animation */
.less-performant {
width: 200px;
height: 200px;
margin-left: 100px;
}
Animation Examples
Here are some practical animation examples:
/* Loading spinner */
.spinner {
width: 40px;
height: 40px;
border: 4px solid rgba(0, 0, 0, 0.1);
border-radius: 50%;
border-top-color: #007bff;
animation: spin 1s ease-in-out infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* Bouncing ball */
.ball {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: #007bff;
animation: bounce 1s ease-in-out infinite;
}
@keyframes bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-100px); }
}
/* Typing effect */
.typing {
overflow: hidden;
border-right: 2px solid #007bff;
white-space: nowrap;
animation: typing 3.5s steps(40, end), blink-caret 0.75s step-end infinite;
}
@keyframes typing {
from { width: 0; }
to { width: 100%; }
}
@keyframes blink-caret {
from, to { border-color: transparent; }
50% { border-color: #007bff; }
}
/* Shake effect */
.shake {
animation: shake 0.5s;
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
10%, 30%, 50%, 70%, 90% { transform: translateX(-10px); }
20%, 40%, 60%, 80% { transform: translateX(10px); }
}