Font Awesome图标与文本对齐优化:图标左对齐,文本换行不左移
解决Font Awesome图标与文本对齐(文本换行不左移)的问题
嘿,我来帮你搞定这个图标和文本对齐的问题!你现在的代码里图标和文本是 inline 元素,所以文本换行后会跑到最左边,和图标重叠。结合你用的Bootstrap 3,给你几个简单好用的方案:
方案1:用Bootstrap 3内置的.media组件(最省心)
Bootstrap 3本身就有专门处理「图标+文本」布局的.media组件,完全符合你的需求,不用额外写CSS:
修改后的完整代码:
<!DOCTYPE html> <html lang="en"> <head> <script src="https://kit.fontawesome.com/74e8323267.js" crossorigin="anonymous"></script> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="alert alert-warning"> <div class="media"> <div class="media-left"> <i class="fas fa-exclamation fa-2x fa-fw"></i> </div> <div class="media-body"> <font size="4"><b>In observation of the holiday, LCS website will not have updated guidance on Friday, April 10, 2020. Guidance and updates will resume Monday, April 13, 2020.</b></font> </div> </div> </div> </div> </body> </html>
.media-left会把图标固定在左侧,.media-body里的文本换行后会自动保持在图标右侧,不会跑到左边。
方案2:自定义Flex布局(灵活可控)
如果你不想用Bootstrap的组件,也可以自己加几行CSS实现,用flex布局兼容性很好:
在<head>里添加样式:
.icon-align-group { display: flex; align-items: flex-start; /* 让图标和文本顶部对齐,可选 */ gap: 10px; /* 图标和文本的间距,可根据需求调整 */ }
然后修改HTML部分的alert内容:
<div class="container"> <div class="alert alert-warning"> <div class="icon-align-group"> <i class="fas fa-exclamation fa-2x fa-fw"></i> <font size="4"><b>In observation of the holiday, LCS website will not have updated guidance on Friday, April 10, 2020. Guidance and updates will resume Monday, April 13, 2020.</b></font> </div> </div> </div>
方案3:传统Float方法(兼容极老浏览器)
如果需要兼容非常老旧的浏览器,也可以用float实现:
添加CSS样式:
.icon-float-left { float: left; margin-right: 10px; /* 图标右侧的间距 */ } .text-container { overflow: hidden; /* 确保文本不会跑到图标下方 */ }
修改后的HTML:
<div class="container"> <div class="alert alert-warning"> <i class="fas fa-exclamation fa-2x fa-fw icon-float-left"></i> <div class="text-container"> <font size="4"><b>In observation of the holiday, LCS website will not have updated guidance on Friday, April 10, 2020. Guidance and updates will resume Monday, April 13, 2020.</b></font> </div> </div> </div>
内容的提问来源于stack exchange,提问作者L. Cavinder
相关产品推荐
相关产品推荐

