如何实现图片居中、标题与段落置于图片右侧的布局?
解决方案
要实现图片居中且标题段落位于图片右侧的布局,核心是调整HTML结构并正确使用Flex布局,具体修改如下:
调整后的CSS代码
/* 父容器:实现整体居中,同时让图片和文字并排 */ .container { display: flex; justify-content: center; align-items: center; gap: 2rem; /* 图片和文字之间的间距,可自定义 */ } /* 文字容器:让标题和段落正常堆叠 */ .text-content { max-width: 500px; /* 限制文字宽度,避免太宽 */ }
调整后的HTML代码
<div class="container"> <div id="unknowing"> <img src="" height="200" width="350" alt="Ancient Rome相关图片"> </div> <div class="text-content"> <div id="house"> <h1>Ancient Rome</h1> </div> <div id="puzzle"> <p>Ancient Rome was a great civilization, that along with Ancient Greece, contributed to many things in the modern world, like architecture, numbers, letters, and government.</p> </div> </div> </div>
关键说明
- 把图片和文字部分包裹在同一个父容器
.container中,通过display: flex实现横向排列 justify-content: center让整个模块在页面水平居中align-items: center确保图片和文字在垂直方向上居中对齐gap属性用来控制图片和文字之间的间距,比用margin更灵活- 文字部分单独用一个容器包裹,保证标题和段落正常上下堆叠
内容的提问来源于stack exchange,提问作者Nguyen Tran
相关产品推荐
相关产品推荐

