HTML新手求助:如何让图片与title元素内文本并排显示
解决图片与文本块并排显示的问题
你的问题出在父容器.element未设置合适的布局逻辑,仅给子元素加inline-block时,当文本块宽度加图片宽度超出容器范围,就会自动换行。改用Flexbox布局可以轻松实现二者并排且自适应空间:
修改后的完整代码
<!doctype html> <html> <head> <style> .logo { box-shadow: 0px 0px 5px white; border: 1px solid #cccccc; width: 30%; } .main{ width: 100%; padding: 20px; } .element{ background-color:#3c3B37; display: flex; align-items: center; padding: 10px; margin-bottom: 15px; } .title { overflow: hidden; margin-left: 50px; border: 1px solid #cccccc; background: linear-gradient(90deg, #cccccc, white); flex: 1; padding: 0 10px; } .title p { margin: 6px; } </style> </head> <body> <div class="main"> <div class="element"> <img class="logo" src="img_snow.jpg" alt="snow" /> <div class="title"> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop pub </p></div> </div> <div class="element"> <img class="logo" src="img_forest.jpg" alt="forest" /> <div class="title"> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop pub </p></div> </div> <div class="element"> <img class="logo" src="img_mountains.jpg" alt="mountains" /> <div class="title"> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop pub </p></div> </div> </div> </body> </html>
关键修改点
- 给
.element添加display: flex,强制子元素在一行排列;align-items: center确保图片与文本块垂直居中对齐 - 给
.title设置flex: 1,让它自动占据图片之外的剩余空间,避免因内容过长换行 - 给
.element添加内边距和外边距,优化整体视觉间距
内容的提问来源于stack exchange,提问作者zBluee
相关产品推荐
相关产品推荐

