Flexbox布局问题:第二行盒子偏外,需与上方盒子精准居中对齐
Fix: Center Second Row's Image & Text Boxes Between First Row Items
Got it—you want the second row's two boxes to sit perfectly centered in the gap between the first row's outer boxes. Here's how to adjust your flexbox code to make that happen:
Step-by-Step Corrected Code
First, let's complete and tweak your existing CSS, plus add a common HTML structure to match your layout goal:
HTML
<div class="flex-container"> <!-- First Row: Outer Boxes --> <div class="box box-1">First Row Left Box</div> <div class="box box-2">First Row Right Box</div> <!-- Second Row: Image + Text Box Group --> <div class="row-2-group"> <div class="box image-box">Image Box</div> <div class="box text-box">Text Box</div> </div> </div>
CSS
html { font-size: 62.5%; } html, body { margin: 0; padding: 0; height: 100%; } body { font-size: 1.6rem; padding: 2rem; /* Add padding to avoid edge overflow */ } * { box-sizing: border-box; } .flex-container { display: flex; flex-wrap: wrap; /* Allows items to wrap to new rows */ justify-content: space-between; /* Pushes first row boxes to left/right edges */ gap: 1rem; /* Optional: space between first row boxes */ } /* Force the second row group to take full width, wrapping it to a new row */ .row-2-group { flex-basis: 100%; display: flex; justify-content: center; /* Centers the image and text boxes in this row */ gap: 1.5rem; /* Space between image and text box */ margin-top: 2rem; /* Space between rows */ } /* Optional: Style for boxes to make layout visible */ .box { padding: 2rem 4rem; border: 2px solid #444; background-color: #f5f5f5; }
Why This Works
justify-content: space-betweenon the main flex container pushes the first row's boxes to the left and right edges, creating the empty gap in the middle.flex-basis: 100%on the.row-2-groupforces it to wrap to a new row and take up the full width of the container.justify-content: centeron the.row-2-groupaligns its inner boxes (image and text) perfectly in the center of the container—exactly between the first row's outer boxes.
If your HTML structure is slightly different, just adjust the grouping: the core idea is wrapping the second row's two boxes in a container that takes full width and centers its children.
内容的提问来源于stack exchange,提问作者user9225569
相关产品推荐
相关产品推荐

