如何通过CSS实现文本居左、图片居右的图文并排显示效果
左文右图并排布局实现方案
直接用Flex弹性布局实现即可,不需要改动你已经给.desc2text设置的文本居中样式,代码维护性、适配性都更好。
- 核心逻辑:给文本块、图片块加一个共同的弹性布局父容器,让内部子元素默认横向排列
- 样式兼容:完全保留你已经写好的
text-align: center文本居中效果 - 适配优化:可通过简单的媒体查询实现小屏幕下自动切换为上下排列,移动端体验更好
完整可运行代码
<style> /* 文本图片并排容器 */ .content-wrap { display: flex; align-items: center; /* 文本和图片垂直居中对齐 */ gap: 30px; /* 文本和图片之间的间距,可按需调整数值 */ max-width: 1200px; /* 内容整体最大宽度,根据页面设计调整 */ margin: 0 auto; /* 内容整体在页面居中 */ } .desc2text { text-align: center; width: 48%; /* 文本块宽度占比,可根据设计调整 */ margin: 0; /* 清除p标签默认外边距,避免排版偏移 */ } .goals { width: 48%; /* 图片块宽度占比,和文本宽度加总留出gap的空间即可 */ height: auto; /* 保持图片原始比例,避免拉伸变形 */ display: block; /* 清除图片默认的行内元素下方留白问题 */ } /* 移动端适配:屏幕宽度小于768px时自动切换为上下排列 */ @media (max-width: 768px) { .content-wrap { flex-direction: column; } .desc2text, .goals { width: 100%; } } </style> <!-- 页面结构:将原有文本和图片包裹在弹性容器内 --> <div class="content-wrap"> <p class="desc2text">Sunway Group’s four pillars of sustainability are outlined based on the 17 goals under the United Nations Sustainable Development Goals (UN-SDG). This SDG focuses on developing and expanding renewable energy resources such as sun, wind, hydropower, liquid and solid biofuels, biogas and geothermal. These renewable sources of energy do not emit greenhouse gasses to the atmosphere and therefore are ideal for the environment and human health.</p> <img src="https://assets.sunwaypyramid.com/E-SDGs-Poster1-1577247095101/w960.png" class="goals"> </div>
其他方案说明
也可以通过给两个元素设置
float: left/float: right实现并排效果,但浮动布局会带来父元素高度塌陷、元素错位等问题,后续调整成本高,非特殊场景不推荐使用。
内容的提问来源于stack exchange,提问作者Lax
相关产品推荐
相关产品推荐

