当前位置: 首页 > news >正文

HTML页面中divborder-bottom不占用整个底边,只占用部分宽度

根据豆包提示,有2个方案:使用使用伪元素 ::after,使用 linear-gradient 背景

方案1:通过伪元素 ::after 可以创建一个新的元素,并为其设置样式,模拟只显示一半宽度的底部边框。

解释

  • .half-border 类设置了 position: relative,为伪元素 ::after 提供定位参考。
  • ::after 伪元素的 content: '' 是必需的,用于创建一个空的内容块。
  • position: absolute 使伪元素脱离文档流,bottom: 0 和 left: 0 将其定位到 <div> 元素的左下角。
  • width: 50% 使伪元素的宽度为父元素宽度的一半,border-bottom 设置了底部边框的样式。
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .half-border {
      position: relative;
      width: 200px;
      height: 100px;
      border: 1px solid #ccc;
    }

    .half-border::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      width: 50%;
      border-bottom: 2px solid red;
    }
  </style>
</head>

<body>
  <div class="half-border">这是一个带有半底边边框的 div</div>
</body>

</html>

方案2:使用 linear-gradient 背景来模拟底部边框,通过控制渐变的宽度来实现只显示一半的底部边框。

解释

  • linear-gradient(to right, red 50%, transparent 50%) 创建了一个从左到右的渐变,前 50% 为红色,后 50% 为透明。
  • background-size: 100% 2px 设置渐变背景的大小,宽度为 100%,高度为 2px。
  • background-repeat: no-repeat 防止背景重复。
  • background-position: bottom 将渐变背景定位到元素的底部。
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .half-border-gradient {
      width: 200px;
      height: 100px;
      border: 1px solid #ccc;
      background: linear-gradient(to right, transparent 50%,red 50% );//透明渐变开始,红色渐变开始
      background-size: 100% 2px;//宽度,高度
      background-repeat: no-repeat;
      background-position: bottom;
    }
  </style>
</head>

<body>
  <div class="half-border-gradient">这是一个使用渐变模拟半底边边框的 div</div>
</body>

</html>

相关文章:

  • Yashan DB 存储结构
  • 19. 大数据-技术生态简介
  • 前端非技术性场景面试题
  • 第4节: 静态路由与动态路由协议(RIP、OSPF)详解
  • 【javaEE】多线程(进阶)
  • Linux 离线部署Ollama和DeepSeek-r1模型
  • 做一做native层面消息实战Looper,Handler,Message
  • 第一章:欢迎来到 HTML 星球!
  • 嵌入式裸机设计--MCU常用裸机架构有哪些?
  • MySQL的安装及配置
  • abbd:`Nx`、`Lerna` 和 `Turborepo`
  • 内网anaconda如何使用代理,避免网络连接失败?
  • 【软件工程】一篇入门UML建模图(状态图、活动图、构件图、部署图)
  • 如何看torch 和torchvision版本,如何看CUDA的版本,我是ubuntu的系统,建立的环境是py38。
  • Linux下SVN保存密码
  • c语言笔记 静态数据与ELF程序格式
  • 关于C/C++语言的初学者在哪刷题,怎么刷题
  • 在资源有限中逆势突围:从抗战智谋到寒门高考的破局智慧
  • SpringMVC-全局异常处理
  • 程序化广告行业(2/89):从程序化广告深挖数据处理技巧
  • 巴方:印度上周导弹袭击造成至少40名平民死亡
  • 美凯龙:董事兼总经理车建兴被立案调查并留置
  • 中巡组在行动丨①震慑:这些地区有官员落马
  • 印巴战火LIVE丨“快速接近战争状态”:印度袭击巴军事基地,巴启动反制军事行动
  • 巴西总统卢拉将访华
  • 人民日报刊文:守护“技术进步须服务于人性温暖”的文明底线