不,我不相信这是可能的——也就是说,我不知道有一种方法可以使单个元素的边框宽度在其一侧发生变化。 但为什么不使用多个元素呢?
这个想法是把一堆 div 水平堆叠起来,然后只需针对你希望拥有不同宽度的那些元素。
这个解决方案将简单地使悬停的 div 具有 10px 厚的边框。请注意,div 之间的空格(它们都在同一行上)不存在——它们之间的空格会导致颜色线上有间隙。
您会看到,我使用了每个 div 都共有的类(border)。我另外使用了一个类来指定颜色,以及另一个类来指定默认厚度。
最后,我将屏幕宽度(100%)除以我拥有的 div 数量(4)。由于您有 8 种不同的颜色,因此您需要将宽度设置为 12.5%,而不是 25%。
<!DOCTYPE html>
<html>
<head>
<style>
.border
{
border-top: solid 5px transparent;
width: 25%;
display: inline-block;
padding: 0px;
margin: 0px;
}
.border:hover
{
border-top-width: 10px;
}
.thick
{
border-top-width: 7px;
}
.thin
{
border-top-width: 3px;
}
.red
{
border-color: red;
}
.blue
{
border-color: blue;
}
.yellow
{
border-color: yellow;
}
.green
{
border-color: green;
}
</style>
</head>
<body>
<div class='border red thick'></div><div class='border blue thin'></div><div class='border green'></div><div class='border yellow'></div>
</body>
</html>
看看这篇文章。他们建议使用伪元素而不是边框图像来实现与您的 HR 类似的方式 http://www.sitepoint.com/rainbow-border-with-sass/。
虽然可以使用边框图像,但它的支持有限 (http://caniuse.com/border-image) 如果您对此方法感兴趣,请查看此代码笔 - http://codepen.io/samarkandiy/pen/lvrBn
这里有一些我制作的东西,向您展示它如何工作 - http://jsfiddle.net/29gPg/
.border {
background-color: black;
background-size: 50px 50px;
display: inline;
float: left;
margin: 15px;
position: relative;
border-width: 20px;
width: 160px;
height: 160px;
}
.border {
border-image: linear-gradient(90deg,
#9b59b6 0%,
#9b59b6 25%,
#34495e 25%,
#34495e 50%,
#f1c40f 50%,
#f1c40f 75%,
#e67e22 75%
) 2%;
border-top-width: 10px;
border-bottom: 0px;
border-left: 0px;
border-right: 0px;
}
然而,有一个技巧可以使用,那就是使用相同的渐变(这次使用正确的浏览器前缀)作为背景图像并将其正确定位。您可以在下面的fiddle中查看结果,如果要设置各种颜色,则必须编写JS / JQuery脚本以动态构建渐变,然后将其应用于元素内联,或者像我一样制作预先确定的类,然后可以随意应用它们(这通常是出于速度和内存原因的首选方法,但出于灵活性考虑,您可能需要选择第一种选项)。
我手动构建了我的第一个渐变,然后使用http://www.colorzilla.com/gradient-editor/获取了所有浏览器前缀(这是我经常使用的一个很棒的工具)。
HTML:
<div id="box"></div>
CSS:
#box {
background-color: black;
margin: 15px;
position: relative;
width: 90%;
height: 40px;
padding: 0;
}
.border_section{
height: 4px;
display: block;
float: left;
}
JavaScript:
var sections = Math.ceil(Math.random()*20);
var target_div = document.getElementById('box');
var target_width = target_div.offsetWidth;
var sec_width = Math.ceil(target_width/sections);
for(i=0;i<sections;i++){
if(i == sections-1){
sec_width = target_width - ((sections-1)*sec_width)-1;
}
var borderSection=document.createElement("span");
borderSection.className = "border_section";
borderSection.style.backgroundColor = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);
borderSection.style.width = sec_width+'px';
target_div.appendChild(borderSection);
}
border-image
,虽然我不确定规范是否允许这样做(而且现在懒得研究)。另一种选择是完全按照该示例使用它 - 只需在要具有此顶部边框的元素顶部放置一个生成的内容伪元素,以便无需将额外元素插入到标记中。 - CBroe