使用display:flex无法实现文本左图片右水平排列,求排查原因
The main issue here is incorrect nesting in your HTML structure. Your .cover div (holding the image) is nested inside the .introduction div—this means your flex container .presentation only has one direct child element (<div class="introduction">). Flexbox arranges direct children of the container, so there’s nothing for it to lay out horizontally right now!
The Fix: Adjust Your HTML Structure
Move the .cover div outside of the .introduction div so that .presentation has two direct children: one for your text/buttons, and one for the image. Here’s the corrected HTML:
<main> <section class="presentation"> <div class="introduction"> <div class="intro-text"> <h1>mac</h1> <p>This is the latest laptop and this laptop is the best ever until nobody doubt that want to mac. This is very powerfull, strong and almost 8k</p> </div> <div class="cta"> <button class="cta-select">14-inch</button> <button class="cta-add">Add Cart</button> </div> </div> <!-- Now .cover is a direct child of .presentation --> <div class="cover"> <img src="https://bhrigu.me/images/mac.png" alt="laptop mac"> </div> </section> </main>
Verify Your CSS (It’s Mostly Correct!)
Your existing CSS will work perfectly with the fixed HTML, but here’s a slightly refined version with a helpful addition:
.presentation { display: flex; width: 90%; margin: auto; min-height: 80vh; align-items: center; /* Add gap to space out text and image */ gap: 2rem; } .introduction { flex: 1; } /* Takes available space for text content */ .cover img { height: 60vh; } /* Image size remains unchanged */
The gap property adds consistent space between your text section and the image, improving visual flow.
Why This Works
With the corrected structure, .presentation now has two flex items:
.introductionusesflex:1to grow and fill the available space for your text and buttons..covertakes up space based on its image content.
Flexbox will automatically arrange these two items horizontally, giving you the left-aligned text and right-aligned image you wanted.
If you still run into issues, double-check that no other CSS rules are overriding your flex properties (like float on the children or position:absolute, which can break flex layout).
内容的提问来源于stack exchange,提问作者vinvincodes

