You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS实现HTML同Section内堆叠列的响应式网页设计问题

Hey there! Let's get that two-column section responsive using modern CSS—here are two straightforward, maintainable approaches that work perfectly with your existing HTML structure:

Approach 1: Flexbox (Great for Flexible Control)

Flexbox is a reliable choice for responsive layouts, giving you granular control over how columns shrink/grow and wrap. Add this to your CSS:

/* Style the section container to act as a flex parent */
section {
  display: flex;
  flex-wrap: wrap; /* Lets columns wrap when space runs out */
  gap: 1.5rem; /* Space between columns (adjust to your design) */
  padding: 1rem; /* Adds inner spacing to the section */
}

/* Default styles for desktop columns */
.col1, .col2 {
  flex: 1 1 48%; /* Grow to fill space, shrink if needed, base width 48% */
  min-width: 280px; /* Prevent columns from getting too narrow on small screens */
}

/* Mobile breakpoint: switch to single column */
@media (max-width: 768px) {
  .col1, .col2 {
    flex: 1 1 100%; /* Full width on mobile */
  }
}

How this works:

  • flex-wrap: wrap ensures columns stack vertically when there's not enough horizontal space.
  • flex: 1 1 48% keeps columns roughly equal width on desktop (we use 48% instead of 50% to account for the gap).
  • min-width prevents columns from becoming unreadably thin on medium-sized screens.
Approach 2: CSS Grid (Cleaner, Less Code)

CSS Grid is even more intuitive for column-based layouts, and it can handle responsiveness without explicit media queries in many cases:

section {
  display: grid;
  /* Auto-fit columns that are at least 280px wide, sharing available space */
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1.5rem;
  padding: 1rem;
}

How this works:

  • repeat(auto-fit, minmax(280px, 1fr)) automatically creates as many columns as fit in the container. Each column is at least 280px wide, and any extra space is divided equally between columns.
  • On mobile screens, the container will only fit one column, so it automatically stacks—no media query needed!

Pro Tips to Polish the Layout

  • Make images responsive: Add img { max-width: 100%; height: auto; } to your CSS to prevent images from overflowing their columns.
  • Adjust gap and padding values to match your design system (e.g., use 2rem instead of 1.5rem for more space).
  • If you need a custom breakpoint (e.g., tablets), add a media query to tweak grid-template-columns or flex-basis for that screen size.

内容的提问来源于stack exchange,提问作者D.Ronald

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:58:10