如何在766px媒体查询下实现标题与图标并排、内容下移?
问题描述
现有一段包含标题、图标和内容的HTML代码,当前显示为标题、图标、内容横向排列;需求是仅在窗口宽度≤766px时,让标题与图标并排显示,内容移至标题下方。即使移除原CSS中的display: flex;属性,仍无法调整标题位置,求解决方案。
解决方案
通过修改响应式媒体查询内的布局规则,调整元素排列方式即可实现需求,核心调整如下:
修改后的完整CSS代码
.article { display: flex; position: relative; overflow: hidden; padding: 0px 8px 0px 8px; } .title { width: 100px; float: left; } .title h3 { padding-right: 24px; } .icon, .content { margin: 18px 0px 0px 18px; } .icon { border-radius: 14px; height: 28px; width: 28px; color: #fff; background-color: #770000; padding: 4px; margin-left: -28px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; /* 让图标居中显示 */ } .content { padding: 13px 13px 13px 13px; max-width: 585px; background: #f4efef; border: 1px solid #e2e2e2; color: #000; } .content::before { content: ''; position: absolute; height: calc(100% + 28px); width: 2px; background: #2dd293; margin-top: 30px; margin-left: -48px; } .article:last-child .content::before { display: none; } @media (max-width: 766px) { .article { flex-direction: column; /* 整体改为纵向排列 */ padding-left: 0; } .title { display: flex; /* 标题和图标横向并排 */ align-items: center; width: auto; /* 取消固定宽度 */ margin-left: 8px; } .icon { margin-left: 12px; /* 调整标题与图标间距,取消负margin */ margin-top: 0; /* 取消顶部margin,和标题垂直居中对齐 */ } .content { width: calc(100% - 80px); /* 适配移动端宽度 */ margin-left: 40px; /* 左侧缩进,保留竖线位置 */ margin-top: 8px; /* 和标题行拉开间距 */ } .content::before { margin-left: -32px; /* 调整竖线位置 */ height: calc(100% + 10px); /* 适配新布局的竖线高度 */ } }
HTML代码(无需修改)
<div class="myList"> <div class="article"> <div class="title"> <h3>Mars</h3> </div> <div class="icon"> <i class="fas fa-mars"></i> </div> <div class="content"> <p>Mars is the fourth planet and the furthest terrestrial planet from the Sun.:</p> </div> </div> </div>
效果说明
- 当窗口宽度大于766px时,保持原有横向排列的显示效果
- 当窗口宽度≤766px时,标题与图标横向并排,内容块自动移至标题下方,同时保留原有的竖线装饰效果
内容的提问来源于stack exchange,提问作者user22142160
相关产品推荐
相关产品推荐

