如何实现响应式图片布局:<1100px垂直,≥1100px横向并排?
Hey Terry! I see you're building a portfolio for your school project and need your project images to stack vertically on screens narrower than 1100px, then line up horizontally once the screen hits that width. Let's tweak your code to make that work perfectly.
First, a quick heads-up: you’re using the same id="project-container" multiple times, but HTML IDs need to be unique. Let’s swap those for a class instead to avoid any unexpected behavior.
Here’s the revised, fully functional code:
Updated HTML
<section id="projects"> <h2 class="subheading">PROJECTS</h2> <div class="project-container"> <a href="project-1/index.html"><img src="images/project-1.jpg" alt="Terry's Computers" class="project-img"></a> </div> <div class="project-container"> <a href="#"><img src="images/coming-soon.jpg" alt="Project Coming Soon" class="project-img"></a> </div> <div class="project-container"> <a href="#"><img src="images/coming-soon.jpg" alt="Project Coming Soon" class="project-img"></a> </div> </section>
Updated CSS
#projects { background-color: #7A0000; border-bottom: 3px solid black; padding: 15px; /* Default layout: stack projects vertically */ display: flex; flex-direction: column; align-items: center; } .project-container { margin: 15px 0; } .project-img { width: 325px; border: 3px solid black; transition: 0.3s; background-color: #333; } .project-img:hover { transform: scale(1.03, 1.03); transition: 0.3s; } /* Desktop layout: line up projects horizontally */ @media screen and (min-width: 1100px) { #projects { flex-direction: row; justify-content: center; gap: 20px; /* Adds clean spacing between projects */ flex-wrap: wrap; /* Lets extra projects wrap to a new line if needed */ } }
Key Changes Breakdown:
- Unique Classes: Replaced repeated
id="project-container"withclass="project-container"to follow HTML best practices. - Base Flex Layout: Set
#projectsto use flexbox withflex-direction: columnby default, which keeps projects stacked vertically and centered on small screens. - Desktop Media Query: When the screen hits 1100px, we switch
flex-directiontorowto line up projects horizontally. Thegapproperty ensures consistent spacing, andflex-wrapprevents overflow if you add more projects later. - Margin Adjustments: Moved margin from
.project-imgto.project-containerfor better spacing control with flexbox.
This setup will give you exactly the responsive behavior you want—clean vertical stacking on mobile, neat horizontal alignment on desktop—while keeping your hover scale effect intact.
内容的提问来源于stack exchange,提问作者TerryJ26

