需求 设置一个小于宽度的边框
使用嵌套的两个元素,在子元素中设置边框以模仿一个小于宽度的效果(优点是简单,但会使用标签可能影响布局)
<div style="width: 100px; display: flex; justify-content: center; background: tan"> <div style="width: 80px; border-bottom: 1px solid black">内容</div> </div>在伪元素中设置一条‘线’做边框(& 是sass\less用法 优点是4个方向都可以,缺点是占用伪元素)
<body> <style type="text/css"> .test { position: relative; //z-index: 2; //如果上级元素中有background需设置 &::before { content: ''; bottom: 0; left: 0; right: 0; width: 50px; height: 2px; position: absolute; z-index: 1; background: #888888; } }</style> <div class='test'> test </div> </body>3种方式中唯一真正实现“小于宽度的边框” 使用 css 中 border-image设置边框,下面是使用 linear-gradient 来实现边框效果(优点是没有上面2种的缺点,问题是左右不可控)
//下边框 width: 100px; background: tan; border-image: 0 0 100% 0 linear-gradient(90deg, transparent 4.2vw, #ddd 0, #ddd 95.8vw, transparent 0, transparent 100vw); border-bottom: 1px solid transparent; //上边框 width: 100px; background: tan; border-image: 100% 0 0 linear-gradient(90deg, transparent 10px, rgb(40, 44, 52) 0, rgb(40, 44, 52) 90px, transparent 0, transparent 100px); border-top: 1px solid transparent;