CSS Intermediate Content
This content has been divided into two parts for better readability:
- Part 1: Layout Techniques, Flexbox, and CSS Grid
- Part 2 (Current): Positioning, Responsive Design, Transitions, Animations, Transforms, Modern CSS Features, and Practice Exercises
CSS Positioning
CSS positioning allows you to control the position of elements on a web page. The position
property specifies the positioning method used for an element.
Position Values
Value | Description |
---|---|
static |
Default value. Elements are positioned according to the normal flow of the document. |
relative |
The element is positioned relative to its normal position. Setting top, right, bottom, and left properties will adjust the element from its normal position. |
absolute |
The element is positioned relative to its nearest positioned ancestor (an ancestor with position other than static). If no positioned ancestors exist, it's positioned relative to the initial containing block (usually the viewport). |
fixed |
The element is positioned relative to the viewport, meaning it always stays in the same place even if the page is scrolled. |
sticky |
The element is positioned based on the user's scroll position. It behaves like relative until a specified offset position is met, then it behaves like fixed . |
Positioning Examples
Relative Positioning
.relative-box {
position: relative;
top: 20px;
left: 20px;
background-color: #4a6fa5;
color: white;
padding: 20px;
}
Absolute Positioning
.container {
position: relative;
height: 200px;
background-color: #f0f0f0;
padding: 20px;
}
.absolute-box {
position: absolute;
top: 40px;
right: 20px;
background-color: #4a6fa5;
color: white;
padding: 20px;
}
Fixed Positioning
.fixed-box {
position: fixed;
bottom: 20px;
right: 20px;
background-color: #4a6fa5;
color: white;
padding: 20px;
z-index: 100;
}
A fixed positioned element would stay in the same place even when the page is scrolled. This can't be demonstrated effectively in this example.
Sticky Positioning
.sticky-header {
position: sticky;
top: 0;
background-color: #4a6fa5;
color: white;
padding: 10px;
z-index: 100;
}
A sticky positioned element toggles between relative and fixed, depending on the scroll position. It's positioned relative until a given offset position is met in the viewport, then it "sticks" in place (like position: fixed). This can't be demonstrated effectively in this example.
The z-index Property
The z-index
property specifies the stack order of an element (which element should be placed in front of, or behind, the others). It only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky).
.container {
position: relative;
height: 150px;
}
.box {
position: absolute;
width: 100px;
height: 100px;
padding: 10px;
color: white;
}
.box-1 {
background-color: #4a6fa5;
top: 10px;
left: 10px;
z-index: 1;
}
.box-2 {
background-color: #166088;
top: 30px;
left: 30px;
z-index: 2; /* Higher z-index, appears on top */
}
Responsive Design
Responsive web design is an approach to web design that makes web pages render well on a variety of devices and window or screen sizes. It's essential for creating websites that provide an optimal viewing experience across a wide range of devices.
Key Principles of Responsive Design
- Fluid Layouts - Using relative units like percentages instead of fixed units like pixels
- Flexible Images - Images that scale with the size of the viewport
- Media Queries - CSS techniques that apply different styles based on device characteristics
- Mobile-First Approach - Designing for mobile devices first, then enhancing for larger screens
Viewport Meta Tag
The viewport meta tag is essential for responsive design. It tells the browser how to control the page's dimensions and scaling.
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Media Queries
Media queries allow you to apply different styles based on device characteristics, such as width, height, orientation, or resolution.
/* Base styles for all devices */
body {
font-size: 16px;
}
/* Styles for tablets and larger */
@media (min-width: 768px) {
body {
font-size: 18px;
}
}
/* Styles for desktops and larger */
@media (min-width: 1024px) {
body {
font-size: 20px;
}
}
Common Breakpoints
Breakpoints are the points at which your website's content will respond to provide the user with the best possible layout to consume the information. Here are some common breakpoints:
Device | Width | Media Query |
---|---|---|
Mobile Phones | < 768px | @media (max-width: 767px) { ... } |
Tablets | 768px - 1023px | @media (min-width: 768px) and (max-width: 1023px) { ... } |
Desktops | 1024px - 1199px | @media (min-width: 1024px) and (max-width: 1199px) { ... } |
Large Desktops | ≥ 1200px | @media (min-width: 1200px) { ... } |
Responsive Layout Example
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 15px;
}
.row {
display: flex;
flex-wrap: wrap;
margin: 0 -15px;
}
.col {
padding: 0 15px;
width: 100%;
}
/* Mobile first approach */
/* Default is one column for mobile */
/* Tablets (2 columns) */
@media (min-width: 768px) {
.col {
width: 50%;
}
}
/* Desktops (3 columns) */
@media (min-width: 1024px) {
.col {
width: 33.333%;
}
}
Responsive Images
Making images responsive is crucial for a good user experience. Here are some techniques:
Basic Responsive Image
img {
max-width: 100%;
height: auto;
}
Using the picture Element
<picture>
<source media="(min-width: 1024px)" srcset="large.jpg">
<source media="(min-width: 768px)" srcset="medium.jpg">
<img src="small.jpg" alt="Responsive Image">
</picture>
Using srcset and sizes Attributes
<img src="small.jpg"
srcset="small.jpg 500w, medium.jpg 1000w, large.jpg 1500w"
sizes="(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 33vw"
alt="Responsive Image">
Mobile-First Approach
The mobile-first approach means designing for mobile devices first, then progressively enhancing the design for larger screens. This approach has several advantages:
- Forces you to focus on the essential content and functionality
- Ensures a good experience on the most constrained devices
- Often results in cleaner, more efficient code
- Aligns with the way CSS works (styles cascade and can be overridden)
/* Mobile styles (default) */
.container {
padding: 10px;
}
.nav {
display: none; /* Hide navigation on mobile */
}
.mobile-nav-toggle {
display: block; /* Show mobile navigation toggle */
}
/* Tablet styles */
@media (min-width: 768px) {
.container {
padding: 20px;
}
.nav {
display: block; /* Show navigation on tablets */
}
.mobile-nav-toggle {
display: none; /* Hide mobile navigation toggle */
}
}
/* Desktop styles */
@media (min-width: 1024px) {
.container {
padding: 30px;
max-width: 1200px;
margin: 0 auto;
}
}
CSS Transitions and Animations
CSS transitions and animations allow you to create smooth, gradual changes in an element's appearance over time, without using JavaScript.
CSS Transitions
Transitions provide a way to control animation speed when changing CSS properties. Instead of having property changes take effect immediately, you can cause the changes to take place over a period of time.
.button {
background-color: #4a6fa5;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
transition: background-color 0.3s ease, transform 0.3s ease;
}
.button:hover {
background-color: #166088;
transform: scale(1.05);
}
Transition Properties
Property | Description | Example |
---|---|---|
transition-property |
Specifies the name of the CSS property the transition effect is for | transition-property: background-color; |
transition-duration |
Specifies how many seconds or milliseconds the transition effect takes to complete | transition-duration: 0.3s; |
transition-timing-function |
Specifies the speed curve of the transition effect | transition-timing-function: ease; |
transition-delay |
Specifies a delay before the transition effect starts | transition-delay: 0.1s; |
transition |
Shorthand property for setting the four transition properties in a single property | transition: background-color 0.3s ease 0.1s; |
Timing Functions
The transition-timing-function
property specifies the speed curve of the transition effect. The following values are commonly used:
ease
- Slow start, then fast, then slow end (default)linear
- Same speed from start to endease-in
- Slow start, then fast endease-out
- Fast start, then slow endease-in-out
- Slow start and end, fast in the middlecubic-bezier(n,n,n,n)
- Custom timing function
CSS Animations
CSS animations allow you to create more complex animations than transitions. They use keyframes to define the stages of an animation.
/* Define the keyframes */
@keyframes pulse {
0% {
transform: scale(1);
}
50% {
transform: scale(1.1);
}
100% {
transform: scale(1);
}
}
/* Apply the animation to an element */
.pulse-animation {
width: 100px;
height: 100px;
background-color: #4a6fa5;
animation: pulse 2s infinite;
}
Animation Properties
Property | Description | Example |
---|---|---|
animation-name |
Specifies the name of the @keyframes animation | animation-name: pulse; |
animation-duration |
Specifies how many seconds or milliseconds an animation takes to complete one cycle | animation-duration: 2s; |
animation-timing-function |
Specifies the speed curve of the animation | animation-timing-function: ease; |
animation-delay |
Specifies a delay before the animation starts | animation-delay: 0.5s; |
animation-iteration-count |
Specifies the number of times an animation should run | animation-iteration-count: infinite; |
animation-direction |
Specifies whether the animation should play in reverse on alternate cycles | animation-direction: alternate; |
animation-fill-mode |
Specifies what values are applied by the animation outside the time it is executing | animation-fill-mode: forwards; |
animation-play-state |
Specifies whether the animation is running or paused | animation-play-state: paused; |
animation |
Shorthand property for all the animation properties | animation: pulse 2s ease 0.5s infinite alternate; |
Multiple Animations
You can apply multiple animations to a single element by separating them with commas.
@keyframes pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.1); }
}
@keyframes colorChange {
0% { background-color: #4a6fa5; }
50% { background-color: #47b8e0; }
100% { background-color: #4a6fa5; }
}
.multi-animation {
width: 100px;
height: 100px;
animation:
pulse 2s infinite,
colorChange 4s infinite;
}
CSS Transforms
CSS transforms allow you to modify the appearance and position of an element without affecting the flow of the document. You can rotate, scale, skew, or translate an element.
2D Transforms
Function | Description | Example |
---|---|---|
translate(x, y) |
Moves an element from its current position | transform: translate(50px, 100px); |
rotate(angle) |
Rotates an element clockwise at a given angle | transform: rotate(45deg); |
scale(x, y) |
Increases or decreases the size of an element | transform: scale(1.5, 2); |
skew(x-angle, y-angle) |
Skews an element along the X and Y axes | transform: skew(20deg, 10deg); |
matrix() |
Combines all 2D transform methods into one | transform: matrix(1, 0.5, -0.5, 1, 50, 0); |
Transform Examples
.translate {
transform: translate(50px, 20px);
}
.rotate {
transform: rotate(45deg);
}
.scale {
transform: scale(1.5);
}
.skew {
transform: skew(20deg, 10deg);
}
/* Multiple transforms */
.multiple {
transform: translate(50px, 20px) rotate(45deg) scale(1.5);
}
3D Transforms
CSS also supports 3D transforms, which allow you to transform elements in three-dimensional space.
Function | Description | Example |
---|---|---|
rotateX(angle) |
Rotates an element around its X-axis | transform: rotateX(45deg); |
rotateY(angle) |
Rotates an element around its Y-axis | transform: rotateY(45deg); |
rotateZ(angle) |
Rotates an element around its Z-axis | transform: rotateZ(45deg); |
translate3d(x, y, z) |
Moves an element in 3D space | transform: translate3d(10px, 20px, 30px); |
scale3d(x, y, z) |
Scales an element in 3D space | transform: scale3d(1.5, 1.5, 2); |
perspective(n) |
Defines the perspective from which all child elements of the object are viewed | transform: perspective(500px); |
Transform Origin
The transform-origin
property specifies the position of the origin for an element's transformations. By default, the origin is at the center of the element.
.box {
width: 100px;
height: 100px;
background-color: #4a6fa5;
transform: rotate(45deg);
transform-origin: top left; /* Rotate around the top-left corner */
}
Modern CSS Features
CSS has evolved significantly in recent years, introducing many powerful features that make it easier to create complex layouts and designs. Here are some modern CSS features you should know:
CSS Variables (Custom Properties)
CSS variables allow you to store values that you can reuse throughout your stylesheet. They're defined with a double hyphen prefix and accessed using the var()
function.
:root {
--primary-color: #4a6fa5;
--secondary-color: #166088;
--font-size-base: 16px;
--spacing-unit: 8px;
}
.button {
background-color: var(--primary-color);
color: white;
padding: calc(var(--spacing-unit) * 2) calc(var(--spacing-unit) * 3);
font-size: var(--font-size-base);
}
.button:hover {
background-color: var(--secondary-color);
}
CSS Calc Function
The calc()
function allows you to perform calculations when specifying CSS property values.
.container {
width: calc(100% - 40px);
margin: 0 20px;
}
.sidebar {
width: calc(30% - 20px);
}
.content {
width: calc(70% - 20px);
}
CSS Logical Properties
Logical properties and values provide the ability to control layout through logical, rather than physical, direction and dimension mappings. This is particularly useful for creating layouts that work with different writing modes and text directions.
/* Physical properties */
.box {
margin-left: 10px;
padding-top: 20px;
border-right: 1px solid black;
}
/* Logical properties */
.box {
margin-inline-start: 10px;
padding-block-start: 20px;
border-inline-end: 1px solid black;
}
CSS Shapes
CSS Shapes allows you to create non-rectangular shapes, around which inline content can flow.
.circle {
width: 200px;
height: 200px;
background-color: #4a6fa5;
border-radius: 50%;
float: left;
shape-outside: circle(50%);
margin-right: 20px;
}
CSS Grid Layout and Subgrid
Subgrid is a feature of CSS Grid Layout that allows grid items to inherit the grid definition of their parent grid container.
.grid-container {
display: grid;
grid-template-columns: repeat(9, 1fr);
grid-template-rows: repeat(4, minmax(100px, auto));
}
.grid-item {
grid-column: 2 / 7;
grid-row: 2 / 4;
display: grid;
grid-template-columns: subgrid;
grid-template-rows: subgrid;
}
CSS Containment
The contain
property allows you to improve performance by isolating a subtree from the rest of the document.
.component {
contain: content;
}
.strict-component {
contain: strict; /* Equivalent to contain: size layout paint style */
}
CSS Scroll Snap
CSS Scroll Snap provides a way to create well-controlled scroll experiences by declaring scroll positions that elements should snap to.
.container {
scroll-snap-type: y mandatory;
overflow-y: scroll;
height: 100vh;
}
.section {
scroll-snap-align: start;
height: 100vh;
}
CSS Backdrop Filter
The backdrop-filter
property applies filter effects to the area behind an element.
.frosted-glass {
background-color: rgba(255, 255, 255, 0.5);
backdrop-filter: blur(10px);
padding: 20px;
}
CSS Aspect Ratio
The aspect-ratio
property sets a preferred aspect ratio for the box, which will be used in the calculation of auto sizes and some other layout functions.
.video-container {
width: 100%;
aspect-ratio: 16 / 9;
}
.square {
width: 50%;
aspect-ratio: 1 / 1;
}
Practice Exercises
Now that you've learned intermediate CSS concepts, it's time to practice! Here are some exercises to help you reinforce what you've learned.
Exercise 1: Create a Flexbox Layout
Create a responsive navigation bar using Flexbox with the following requirements:
- The navigation should be horizontal on desktop and vertical on mobile (use a media query)
- Include at least 5 navigation items
- Style the navigation items with hover effects using transitions
- Make sure the navigation is centered on the page
Exercise 2: Create a CSS Grid Layout
Create a responsive grid layout for a photo gallery with the following requirements:
- Use CSS Grid to create the layout
- On mobile, display 1 image per row
- On tablets, display 2 images per row
- On desktop, display 4 images per row
- Add hover effects to the images using transforms
Exercise 3: Create an Animated Button
Create a button with the following features:
- Use CSS variables for colors and dimensions
- Add hover and active states with smooth transitions
- Include an icon that moves on hover (using transforms)
- Add a subtle animation that plays when the page loads
Exercise 4: Create a Responsive Card Layout
Create a set of cards for a product listing with the following requirements:
- Each card should include an image, title, description, and button
- Use Flexbox or Grid for the layout
- Make the layout responsive (1 column on mobile, 2 on tablet, 3 on desktop)
- Add hover effects to the cards
- Use CSS variables for consistent styling
Exercise 5: Create a Sticky Header
Create a page with a header that becomes sticky when scrolling down:
- The header should be normal at the top of the page
- When scrolling down, the header should stick to the top of the viewport
- Add a smooth transition when the header becomes sticky
- Make sure the header is responsive