响应式布局调试:如何实现withwithout2区块元素按文本在前、图片在后的顺序堆叠
Fix for Responsive Stacking of
.withwithout2 Section The problem with your current approach is that you're relying on negative margins and inline-block positioning—these are fragile hacks that can break layout across different screen sizes. Instead, we can use CSS Grid's native capabilities to cleanly reorder elements while preserving your desktop layout. Here's how to fix it:
Step 1: Replace the messy mobile styles for .withwithout1 and .withwithout2
Update your max-width: 890px media query with this cleaner, grid-based code:
@media screen and (max-width: 890px) { /* Keep all your existing styles here (nav, startingbackground, etc.) */ /* Fix .withwithout1 to use grid for consistent responsive behavior */ .withwithout1 { display: grid; grid-template-columns: 1fr; /* Single column on mobile */ gap: 2rem; /* Add consistent spacing between text and image */ text-align: center; } .withwithout1right { max-width: 60%; margin: 3rem auto 0; /* Center image without hardcoded left margin */ } /* Fix .withwithout2 to reorder elements on mobile */ .withwithout2 { display: grid; grid-template-columns: 1fr; /* Single column on mobile */ gap: 2rem; /* Space between text and image */ text-align: center; } .withwithout2right { order: -1; /* Move text section above the image */ margin-top: 0; /* Reset negative margin hack */ } .withwithout2left { margin-top: 0; /* Reset top margin hack */ display: flex; justify-content: center; /* Center the image */ } }
Step 2: Why this works
- Desktop layout preserved: For screens larger than 890px, both sections keep their original 2-column grid layout.
- Mobile reordering: On small screens,
grid-template-columns: 1frswitches to a single column. Theorder: -1property on.withwithout2rightmoves the text section before the image, exactly what you need. - Clean spacing: Using
gapinstead of margins ensures consistent spacing between elements without layout shifts.
Optional Improvement
You can set .withwithout { height: auto; } in the mobile media query instead of 100rem—this lets the section height adjust naturally to its content, making it more responsive across devices.
内容的提问来源于stack exchange,提问作者paulman
相关产品推荐
相关产品推荐

