小屏幕下奇数.blog-card卡片图片未置顶问题求助
问题
我制作了一组.blog-card卡片,奇数序号卡片的图片位于卡片右侧,偶数序号卡片的图片位于左侧。在小屏幕尺寸下,仅偶数序号卡片的图片会显示在卡片顶部,奇数序号卡片的图片则被隐藏。全屏状态下4张图片均正常显示,但缩小视口后就会出现上述问题。怀疑和使用的:nth-of-type() CSS伪类有关,求修复建议。
问题分析
问题根源确实和:nth-of-type(odd)的设置有关,但不是伪类本身的问题,而是响应式逻辑冲突:
- 小屏幕下(<640px),
.blog-card默认是flex-direction: column,元素按DOM顺序垂直排列(先图片容器.meta,再文本.description)。 - 但你给奇数卡片设置了全局的
flex-direction: row-reverse,这会让小屏幕下的奇数卡片变成垂直反转排列——先显示.description,再显示.meta。 - 加上
.description的z-index: 1且背景为白色,.meta的z-index: 0,导致.meta被完全盖住,看起来像是图片被隐藏了。
修复方案
只需把奇数卡片的row-reverse布局限定在大屏幕媒体查询内即可,小屏幕统一使用默认的垂直排列:
修改后的CSS代码如下:
.blog-card { display: flex; flex-direction: column; margin: 1rem auto; box-shadow: 0 2px 6px -1px rgba(0, 0, 0, .07), 0 6px 18px -1px rgba(0, 0, 0, .04); margin-bottom: 1.6%; background: #fff; line-height: 1.5; border-radius: 0; overflow: hidden; z-index: 0; } .blog-card:nth-of-type(odd) .description:before { left: inherit; right: -10px; transform: skew(3deg); } .blog-card:hover .photo { transform: scale(1.1) rotate(3deg); } .blog-card .meta { position: relative; z-index: 0; height: 200px; } .blog-card .photo { position: absolute; top: 0; right: 0; bottom: 0; left: 0; background-size: cover; background-position: center; transition: transform 0.3s; } .blog-card .description { padding: 1rem; background: #fff; position: relative; z-index: 1; } .blog-card .description h1, .blog-card .description h2 { font-family: Poppins, sans-serif; } .blog-card .description h1 { line-height: 1; margin: 0; font-size: 1.7rem; } .blog-card .description h2 { font-size: 1rem; font-weight: 300; text-transform: uppercase; color: var(--grey-700); margin-top: 5px; } .blog-card p { position: relative; margin: 1rem 0 0; } .blog-card p:first-of-type { margin-top: 1.25rem; } .blog-card p:first-of-type:before { content: ""; position: absolute; height: 3px; background: var(--brand-color); width: 100px; top: -0.75rem; border-radius: 0; } @media (min-width: 640px) { .blog-card { flex-direction: row; max-width: 900px; } .blog-card:nth-of-type(odd) { flex-direction: row-reverse; } .blog-card .meta { flex-basis: 40%; height: auto; } .blog-card .description { flex-basis: 60%; } .blog-card .description:before { transform: skewX(-3deg); content: ""; background: #fff; width: 30px; position: absolute; left: -10px; top: 0; bottom: 0; z-index: -1; } }
修复逻辑说明
- 小屏幕下所有卡片保持
flex-direction: column,DOM顺序为图片在上、文本在下,不会出现遮挡问题。 - 仅当屏幕宽度≥640px时,给奇数卡片设置
row-reverse,实现图片在右侧的布局,和大屏幕的左右排列逻辑匹配。
如果希望小屏幕下奇数卡片的图片固定在底部,可以保留小屏幕的row-reverse,但需要移除.description的白色背景或调整层级关系,不过这种设计对移动端用户体验不如图片统一在顶部友好。
内容的提问来源于stack exchange,提问作者Hagelslag
相关产品推荐
相关产品推荐

