如何实现HTML卡片标题在移动端的响应式显示
问题原因
- 当前使用
float实现logo与雇主名称的横向排列,float布局在容器宽度不足时会触发元素自动换行,搭配固定的padding-top、固定字号设置,就会出现移动端错位的异常效果 - 未做响应式适配,桌面端20px的标题字号在移动端宽度下会占用过多横向空间,加剧布局错乱
调整方案
第一步:修改HTML代码
移除img和h6标签上的行内float、padding样式,给logo和雇主名称的父容器新增自定义类education-card-header,修改后代码如下:
<div class="col py-2"> <div class="card education-card mirror-face"> <div class="card-body"> <!-- 新增class,移除内部元素的行内样式 --> <div class="education-card-header"> <img class="competence-img" alt="logo" src="{{experience.experience_image.url}}"/> <h6 class="education-card-title">{{experience.employer}}</h6> </div> <h6 class="education-card-title education-card-position">{{experience.title}}</h6> <div> <p class="education-card-desc">{{experience.description}}</p> </div> </div> </div> </div>
第二步:修改CSS代码
用flex布局实现头部的横向排列,新增媒体查询做移动端适配,调整后代码如下:
/* 原有样式保留,新增以下样式 */ .education-card-header { display: flex; align-items: center; gap: 12px; margin-bottom: 8px; flex-wrap: nowrap; /* 强制不换行,避免宽度不足时错位 */ } /* 限制logo最大尺寸,避免占用过多空间 */ .competence-img { max-width: 48px; max-height: 48px; object-fit: contain; flex-shrink: 0; /* 禁止logo被压缩 */ } .education-card-title { color: var(--scolor); font-size: 20px; font-weight: 500; margin: 0; /* 清除默认h6 margin避免布局偏移 */ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; /* 标题过长时显示省略号,避免撑破布局 */ } /* 职位标题不需要强制一行的话可以单独设置 */ .education-card-position { white-space: normal; margin: 8px 0; } .education-card-desc { color: var(--color); font-size: 14px; font-weight: 300; } /* 移动端响应式适配,768px可以根据你的实际断点调整 */ @media (max-width: 768px) { .education-card-title { font-size: 16px; } .competence-img { max-width: 40px; max-height: 40px; } }
调整效果说明
- 采用flex布局替代float,从根源上避免浮动元素换行错位的问题
- 限制logo尺寸、增加文本溢出处理,避免内容撑破容器
- 移动端自动缩小字号和logo尺寸,适配小屏幕显示
- 如果不需要标题过长显示省略号的效果,去掉
white-space: nowrap、text-overflow: ellipsis两个属性即可,文字会自动换行。
内容的提问来源于stack exchange,提问作者A_K
相关产品推荐
相关产品推荐

