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

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

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

解释

  • .half-border 类设置了 position: relative,为伪元素 ::after 提供定位参考。
  • ::after 伪元素的 content: '' 是必需的,用于创建一个空的内容块。
  • position: absolute 使伪元素脱离文档流,bottom: 0left: 0 将其定位到 <div> 元素的左下角。
  • width: 50% 使伪元素的宽度为父元素宽度的一半,border-bottom 设置了底部边框的样式。
html 复制代码
<!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 将渐变背景定位到元素的底部。
html 复制代码
<!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>
相关推荐
UpUpUp……3 小时前
HTML简单语法标签(后续实操:云备份项目)
笔记·html
读心悦6 小时前
CSS结构性伪类、UI伪类与动态伪类全解析:从文档结构到交互状态的精准选择
css·ui·交互
码农黛兮_469 小时前
CSS3 基础知识、原理及与CSS的区别
前端·css·css3
(((φ(◎ロ◎;)φ)))牵丝戏安9 小时前
根据输入的数据渲染柱形图
前端·css·css3·js
逍遥德11 小时前
CSS可以继承的样式汇总
前端·css·ui
读心悦11 小时前
CSS3 选择器完全指南:从基础到高级的元素定位技术
前端·css·css3
_龙衣12 小时前
将 swagger 接口导入 apifox 查看及调试
前端·javascript·css·vue.js·css3
crazyme_614 小时前
前端自学入门:HTML 基础详解与学习路线指引
前端·学习·html
为美好的生活献上中指15 小时前
java每日精进 5.11【WebSocket】
java·javascript·css·网络·sql·websocket·网络协议
海拥✘16 小时前
CodeBuddy终极测评:中国版Cursor的开发革命(含安装指南+HTML游戏实战)
前端·游戏·html