You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何用HTML和CSS实现符合示例样式的卡片组件

卡片组件样式修复方案

需求回顾

需实现的卡片组件规范:

  • 根元素为class="card"的<div>,宽度344px
  • 沙漠图片高度194px
  • 正文与其他元素的内边距为16px
  • 标题文本颜色#000,字号22px
  • 二级文本和正文颜色#232F34,正文字号11px
  • 头像图片直径40px
  • 鼠标悬停卡片时,添加阴影:rgba(0, 0, 0, .3)、水平偏移0px、垂直偏移2px、模糊半径4px

原代码问题点

  1. CSS选择器错误:类名带空格的写法无效(如.card body、.card footer),需改为连字符命名的.card-body、.card-footer;阴影选择器.card card-shadow逻辑错误,应直接给.card添加hover状态的阴影
  2. 尺寸不符:头像设置为50px,不符合直径40px的要求
  3. 布局与内边距错误:卡片根元素设置16px padding导致图片无法占满宽度,内部内容边距未合理分配
  4. 结构冗余:额外添加的.card card-shadow div完全多余,阴影应直接作用于卡片根元素
  5. 文本样式错误:二级文本字号设为22px不符合需求,部分文本对齐设置不合理

修正后的代码

HTML代码

<div class="card">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/8e/Arabian_Desert_-_panoramio.jpg/544px-Arabian_Desert_-_panoramio.jpg" alt="沙漠风景" class="card-image">
  <div class="card-content">
    <div class="card-header">
      <img class="avatar" src="https://png.pngtree.com/png-vector/20220709/ourmid/pngtree-businessman-user-avatar-wearing-suit-with-red-tie-png-image_5809521.png" alt="用户头像">
      <div class="header-text">
        <h3 class="card-title">Title goes here</h3>
        <p class="card-subtitle">Secondary text</p>
      </div>
    </div>
    <p class="card-body">Greyhound divisively hello coldly wonderfully marginally far upon excluding.</p>
  </div>
</div>

CSS代码

.card {
  width: 344px;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  overflow: hidden;
  transition: box-shadow 0.2s ease;
}

.card-image {
  height: 194px;
  object-fit: cover;
  width: 100%;
}

.card-content {
  padding: 16px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.card-title {
  color: #000;
  font-size: 22px;
  margin: 0 0 4px 0;
}

.card-subtitle {
  color: #232F34;
  font-size: 14px;
  margin: 0;
}

.card-body {
  color: #232F34;
  font-size: 11px;
  margin: 0;
  line-height: 1.5;
}

.card:hover {
  box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.3);
}

关键修改说明

  • 统一类名命名规则,用连字符替代空格,确保CSS选择器生效
  • 调整卡片布局:根元素移除padding,内部内容用.card-content包裹并设置16px内边距,保证图片占满卡片宽度
  • 修正头像尺寸为40px,用object-fit: cover避免图片拉伸变形
  • 重构头部布局,通过flex实现头像与文本横向排列,添加合理间距优化排版
  • 将阴影效果绑定到.card:hover状态,移除冗余的阴影div
  • 调整文本margin和行高,匹配需求中的颜色、字号要求,提升可读性

内容的提问来源于stack exchange,提问作者Anonymous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 18:04:53