如何实现响应式并排正方形图片及中间重叠元素布局?
Solution to Your Side-by-Side Square Images with Centered Middle Element
Let's fix those two issues and get your layout working exactly as you want. Here's the corrected implementation:
Updated HTML
<div class="main_container_1"> <div class="row"> <div class="image_cell"> <div class="square-wrapper"> <img src="http://placehold.it/450x200" alt="Left image"> </div> </div> <div class="image_cell"> <div class="square-wrapper"> <img src="http://placehold.it/200x200" alt="Right image"> </div> </div> <div class="text-cell"> <div class="inner"> text </div> </div> </div> </div>
Updated CSS
.main_container_1 { position: relative; /* Changed from absolute to relative */ width: 100%; margin: 10px; padding: 10px; background-color: lime; } .row { position: relative; /* Makes this the positioning context for text-cell */ display: flex; width: 100%; background-color: yellow; } .image_cell { width: 50%; overflow: hidden; } .square-wrapper { position: relative; width: 100%; padding-top: 100%; /* Creates a square aspect ratio (height = width) */ } .square-wrapper img { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; /* Ensures image fills the square without distortion */ } .text-cell { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); /* Perfectly centers the element */ z-index: 10; /* Ensures it sits on top of the images */ display: flex; justify-content: center; align-items: center; background: white; } .inner { width: 50px; height: 50px; background-color: red; }
Key Fixes Explained
Consistent Square Sizes:
- We added a
square-wrapperdiv withpadding-top: 100%—this trick forces the container to maintain a 1:1 aspect ratio (square) regardless of the image's original dimensions. - The image is absolutely positioned inside the wrapper and uses
object-fit: coverto fill the square without stretching (it will crop the image if needed to fit perfectly).
- We added a
Centered Middle Icon:
- Changed the
.rowtoposition: relativeso the.text-cellis positioned relative to the row (not the entire main container). - Used
top: 50%,left: 50%, andtransform: translate(-50%, -50%)to perfectly center the middle element both horizontally and vertically. - Added
z-index:10to make sure the icon sits above the images.
- Changed the
No Fixed Dimensions:
- Removed the fixed
height:600pxfrom.main_container_1and changed it toposition: relative—now the container will adapt to its content and the available width.
- Removed the fixed
This implementation will meet all your requirements: two square images filling the container width, adaptive height, centered middle element, and no fixed container dimensions.
内容的提问来源于stack exchange,提问作者Rafael Morillo
相关产品推荐
相关产品推荐

