惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

K
Kaspersky official blog
Engineering at Meta
Engineering at Meta
D
DataBreaches.Net
Stack Overflow Blog
Stack Overflow Blog
Microsoft Security Blog
Microsoft Security Blog
Y
Y Combinator Blog
B
Blog RSS Feed
GbyAI
GbyAI
P
Proofpoint News Feed
aimingoo的专栏
aimingoo的专栏
MyScale Blog
MyScale Blog
D
Docker
阮一峰的网络日志
阮一峰的网络日志
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recorded Future
Recorded Future
美团技术团队
The Register - Security
The Register - Security
V
Visual Studio Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Tailwind CSS Blog
爱范儿
爱范儿
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
The Blog of Author Tim Ferriss
博客园 - 司徒正美
量子位
B
Blog
F
Fortinet All Blogs
Martin Fowler
Martin Fowler
博客园 - 【当耐特】
MongoDB | Blog
MongoDB | Blog
A
About on SuperTechFans
I
InfoQ
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
有赞技术团队
有赞技术团队
雷峰网
雷峰网
大猫的无限游戏
大猫的无限游戏
J
Java Code Geeks
L
LangChain Blog
Latest news
Latest news
S
SegmentFault 最新的问题
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Blog — PlanetScale
Blog — PlanetScale
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cisco Talos Blog
Cisco Talos Blog
F
Full Disclosure
C
Cisco Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
W
WeLiveSecurity
T
Tenable Blog
T
Tor Project blog

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

Learn Command Line Interface (CLI) Development with Dart: From Zero to a Fully Published Developer Tool How to Build a Live Options Database in Python – A Complete Guide How to Migrate to S3 Native State Locking in Terraform How to Use SCons to Build Software Projects [Full Handbook] How to Run Open Source LLMs Locally and in the Cloud QuRT: The Real-Time OS Inside Your Phone's Processor [Full Handbook] The Real Infrastructure Behind Remote Work (It’s Not Just Wi-Fi) The Lithography Handbook: Machines, Markets, and the Next Wave of Semiconductor Startups ITCM vs DTCM vs DDR: Embedded Memory Types Explained [Full Handbook] AI Paper Review: Improving Language Understanding by Generative Pre-Training (GPT-1) How to Build a Market Research Copilot with MCP and Python [Full Handbook] How to Build a Scoped Note-Taking API with Django Rest Framework and SimpleJWT The Complete SOC 2 Type II Implementation Handbook for Engineers: A Month-by-Month Roadmap with Real Commands Mastering the JavaScript Event Loop Data Science Insights: Why the Mean Lies When Handling Messy Retail Data How to Build High-Ranking SEO Landing Page How to Query Data in DynamoDB Using .Net How to Unblock Your AI PR Review Bottleneck: A Tech Lead’s Guide to Building a Codebase-Aware Reviewer How to Navigate Microservices as a Frontend Engineer How to Compress PDF Files in the Browser Using JavaScript (Step-by-Step) Stanford's youngest instructor talks InfoSec, AI, and catching cheaters - Rachel Fernandez interview [Podcast #217] Product Experimentation with Propensity Scores: Causal Inference for LLM-Based Features in Python How to Build a Multi-Agent AI System with LangGraph, MCP, and A2A [Full Book] How to Land Your First Cloud or DevOps Role: What Hiring Managers Actually Look For How to Deploy a Serverless Spam Classifier Using Scikit-Learn, AWS Lambda, & API Gateway How to Dockerize a Go Application – Full Step-by-Step Walkthrough Learn Hardware, Cloud, DevOps, Networking, Security, Databases, DNS, Git, and Linux Inside TreeHacks 2026, Stanford’s Elite Student Hakc Inside Stanford’s Elite Student Hackathon [Full Documentary] How to Measure Your AI Citation Rate Across ChatGPT, Perplexity, and Claude How to Deploy a Full-Stack Next.js App on Cloudflare Workers with GitHub Actions CI/CD How to Build a Multi-Tenant SaaS Platform with Next.js, Express, and Prisma How I Completed 15 freeCodeCamp Certifications in 4 Months: A Structured Learning Journey How to Build an Agentic Terminal Workflow with GitHub Copilot CLI and MCP Servers How AI Changed the Economics of Writing Clean Code How to Apply STRIDE Threat Modeling and SonarQube Analysis for Secure Software Development How to Set Up OpenID Connect (OIDC) in GitHub Actions for AWS How to Split PDF Files in the Browser Using JavaScript (Step-by-Step) How to Build Your Own Language-Specific LLM [Full Handbook] How to Build a Self-Learning RAG System with Knowledge Reflection How to Trace Multi-Agent AI Swarms with Jaeger v2 How I Tested Malaysia's Open Data Portals with Plain English How I Built a Production-Ready CI/CD Pipeline for a Monorepo-Based Microservices System with Jenkins, Docker Compose, and Traefik The Hidden Tax of Infrastructure: Why Your Team Shouldn’t Be Running It Anymore From Metrics to Meaning: How PaaS Helps Developers Understand Production From Symptoms to Root Cause: How to Use the 5 Whys Technique Product Experimentation for AI Rollouts: Why A/B Testing Breaks and How Difference-in-Differences in Python Fixes It How to Create a GPU-Optimized Machine Image with HashiCorp Packer on GCP 3D Web Development with Blender and Three.js How to Fix a Failing GitHub PR: Debugging CI, Lint Errors, and Build Errors Step by Step How to Merge PDF Files in the Browser Using JavaScript (Step-by-Step) How to Handle Stripe Webhooks Reliably with Background Jobs How to Build an Automatic Knowledge Graph for Your Blog with PHP and JSON-LD Understanding Proxies and Reverse Proxies: Your Gateway to Secure Networking The Evolution of Nvidia Blackwell GPU Memory Architecture How to Use PostgreSQL as a Cache, Queue, and Search Engine The New Definition of Software Engineering in the Age of AI Reclaim Your Time – Master Automation with Zapier How to Create Dynamic Emails in Go with React Email Why Many Beginner Self-Taught Developers Struggle (And What to Do About It) How to Build a Headless WordPress Frontend with Astro SSR on Cloudflare Pages How to Make Your GitHub Profile Stand Out How to Use Context Hub (chub) to Build a Companion Relevance Engine Why Chrome OS Is the Operating System the AI Era Was Built For How to Build Microservices-Based REST APIs for Healthcare Portals How to friction-max your learning with software engineer Jessica Rose [Podcast #216] Shadow AI Explained: Why Employees Are Using AI Behind Your Back Traditional Scraping vs AI Scraping: A Practical Guide for Developers and Data Teams How Database Indexes Work – A Practical Guide with PostgreSQL Examples How to Streamline Search in Web Applications with Elasticsearch How to Build an Open Source Data Lake for Batch Ingestion OpenAI Codex Essentials – AI Assisted Agentic Development Course Learn Software System Design How to Generate PDF Files in the Browser Using JavaScript (With a Real Invoice Example) How to Get Started with Terraform Service-to-Service Communication: When to Use REST, gRPC, and Event-Driven Messaging A Developer’s Guide to Lazy Loading in React and Next.js The Data Quality Handbook: Data Errors, the Developer's Role, and Validation Layers Explained. United States Residential Proxy: Why Local IP Accuracy Matters for SERP, Ads, and Pricing How to Build a Fashion App That Helps You Organize Your Wardrobe How to Build an Admin Dashboard Sidebar with shadcn/ui and Base UI The AI Governance Handbook: How to Build Responsible AI Systems That Actually Ship How to Build a Local DevOps HomeLab with Docker, Kubernetes, and Ansible How to Use Mixins in Flutter [Full Handbook] How to Prep for Technical Interviews – A Guide for Web Developers GPT-5.4 vs GLM-5: Is Open Source Finally Matching Proprietary AI? Data Visualization Tools for Svelte Developers How to Keep Human Experts Visible in Your AI-Assisted Codebase Efficient Data Processing in Python: Batch vs Streaming Pipelines Explained How to Build and Deploy Multi-Architecture Docker Apps on Google Cloud Using ARM Nodes (Without QEMU) How to Build a Secure AI PR Reviewer with Claude, GitHub Actions, and JavaScript How to Build a Positioning-Based Crude Oil Strategy in Python [Full Handbook] How to learn programming and CS in the AI hype era – interview with dev and prof Mark Mahoney [Podcast #215] CUDA Programming for NVIDIA H100s How to Build Reliable AI Systems. How to Build an Online Marketplace with Next.js, Express, and Stripe Connect How to Build a Cost-Efficient AI Agent with Tiered Model Routing The WebCodecs Handbook: Native Video Processing in the Browser The Bluetooth LE Audio Handbook: From "Why Does My Call Sound Like a Tin Can?" to AOSP Implementation How to Set Up OpenClaw and Design an A2A Plugin Bridge
How to Build Responsive Designs and Scroll Effects with CSS Container Queries
jabo Landry · 2026-06-03 · via freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
How to Build Responsive Designs and Scroll Effects with CSS Container Queries

Container queries let you target specific sections of your webpage and apply styles to create customizable, responsive designs based on the container's size rather than that of the viewport.

This guide will teach you this useful alternative for responsive designs. You'll also learn about on-scroll effects in CSS.

Prerequisites

Before diving into scrollable queries and container-based scroll effects, make sure you have:

  • Basic familiarity with CSS features and key terms — understanding properties like height, overflow, and how they affect layout.

  • Experience writing vanilla CSS — being comfortable with selectors, rulesets, and applying styles without relying on frameworks.

  • A working knowledge of HTML structure — since scroll behavior depends on parent elements, knowing how containers and child elements interact is essential.

  • (Optional but helpful) Some exposure to responsive design concepts, so you can see how scrollable parents fit into broader layout strategies.

What We'll Cover:

  • Prerequisites

  • How to Use Container Queries

  • Difference Between Container Queries and Media queries

  • Container Scroll-state

  • Wrapping Up

Usually, when making responsive designs, you use a media query that adds style to the page based on the page's width viewport, but container queries shift the narrative by adding styles based on the specific elements container or parent element size.

Take a navbar as an example. Let's say you want to have its links wrapped on top of each other when the size of a nav element size is less than 450px and also change the background color when the screen size is less than 450px.

To make nav element links wrap on top of each other when the nav element size is less than 450px, we start by wrapping the links inside a single parent nav:

   <nav>
      <img src="" alt="logo" />
      <ul>
        <a href="">home</a>
        <a href="">about</a>
        <a href="">services</a>
        <a href="">contact</a>
      </ul>
    </nav>

Then use container-type to define a container query on the wrapping element or parent (nav) element. It can have one of the following values:

  • inline-size: Used when you want to track the x-axis of the parent element on the page (width)

  • block-size: Used when you want to track the y-axis of the parent element on the page (height)

  • Container Scroll-state: Used when you want to track the parent element when scrolled and when elements with position sticky are stuck on the screen.

For most cases, you will need to track the size of an element against the x-axis size, and you must use the container-type on a parent element because you want to apply styles based on the parent element size. Here, we'll use the nav because it is the parent element.

nav { 
  container-type: inline-size;
}

You then define a container query with an at symbol (@) followed by the container keyword.

Then check if the width of the parent container (nav) gets narrower than 450px. If the condition is true, add a flex-wrap to links element:

@container (width > 450px) {
  ul {
    flex-wrap: wrap;
  }
}

Take a look at the code below for media queries:


@media (width < 450px) {
  nav {
    background: green;
  }
}

In the media query above, the nav element has a green background-color when the screen size is less than 450px.

For container queries, the elements are getting stacked on top of each other when the nav element size is less than 450px.

So, the difference is that media-queries considers the whole screen size while container-queries consider the parent element size.

Example:

You can also use container queries to style an element on scroll or to style an element with a position sticky when it's stuck on the page.

Note: Container scroll-state browser support isn't very good. It's supported in about 71% of all browsers currently, with the notable exceptions of Safari and Firefox. Be cautious when using it in production.

Scrollable Queries

A scrollable query is used to check for parent element scrollbar behavior. If there is a scroll behavior on the parent element, then the container query for scrolling will be applied.

To use the scrollable queries, you need to have a parent that has a scroll behavior. HTML is the best fit for such an example because by default HTML has a scroll behavior on it.

To make an element scrollable, set a fixed height and apply overflow. This ensures a scroll bar appears whenever content exceeds that defined space.

Example:

We’ll design a simple page that displays a sidebar table of contents when the page is scrolled down and hides it when the user returns to the top.

First, make HTML a container-type of scroll-state:

html {
  container-type: scroll-state;
}

Style the table of contents section and position it at the top right of the page.

.toc {
  position: fixed;
  top: 5rem;
  left:90%;
  align-self: start;
  opacity: 0;
}

You positioned the table of contents to the right of the page and fixed it to the top of the screen by 5rem. You also hid it by default by adding an opacity of 0.

Now you need to check if the container scrollbar can be scrolled to the top of its container. If true, unhide the table of contents:

@container scroll-state(scrollable: top) {
  .toc {
    transition: opacity 0.4s linear;
    opacity: 1;  
  }
}

You defined a container query, then followed it with the scroll-state keyword. This checks whether the scrollbar on a parent element can be scrolled.

Use scrollable to define the scroll direction. Setting it to top tests whether the container can scroll upward, while setting it to bottom tests whether it can scroll downward.

You can see that as long there's a space for scrolling to the top, the table-of- contents will be visible, but when you can't scroll to the top, the table of contents will be hidden.

You can also check whether you can scroll in both top and bottom directions using the y specifier to specify the container's top and bottom scroll directions.

Example:

You can see from the example that the table of contents will always be visible on the screen because the scroll bar can scroll both ways (top and bottom)

Stuck Queries

Stuck queries are used to inspect the element that have a position of sticky and applies styles when the element is stuck on the page.

These are great if you want to style elements that have a sticky position and you want them to have a certain style(s) when they get stuck on the page.

Example:

We'll design a simple navbar that will change its box-shadow when its stuck at the top of the screen.

Here, you'll set a wrapper element that wraps nav and makes it a container query, and also gives it a position of sticky to be able to track if it is stuck at the top of the screen.

header {
  position: sticky;
  top: 0rem;
  container-type: scroll-state;
}

You can then define @container to execute when the element gets stuck on the screen:

@container scroll-state(stuck:top) {
  nav {
    box-shadow:
      0 14px 28px rgba(0, 0, 0, 0.55),
      0 1px 0 rgba(255, 255, 255, 0.06) inset;
    background-color: #0a0a0a;
  }
}

You checked for scroll-state behavior and then, inside the parenthesis, checked if the element with position: sticky is stuck at top of the page. If true, the background color of the nav changes and a box-shadow is added.

Final results should look like this:

By default, the nav doesn't have a box-shadow, but when you scroll and the nav element gets stuck at the top of the page, box-shadow and other rules defined within the stuck @container query definition will be applied to the nav element.

Wrapping Up

In this article, you learned how to set up and work with container queries to make more customizable and responsive designs, and some cool scroll effects.

The examples provided in this guide are not the only things you can do with container queries. The examples were designed to help you think of other alternatives and contexts where you can apply container queries to match your exact needs and design.

Container queries have high browser support, which is currently at 95% and supported in all major browsers.



Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started