边框不支持百分比.但仍有可能...
正如其他人指出的CSS specification,边框不支持百分比:
'border-top-width',
'border-right-width',
'border-bottom-width',
'border-left-width'
Value: <border-width> | inherit
Initial: medium
Applies to: all elements
Inherited: no
Percentages: N/A
Media: visual
Computed value: absolute length; '0' if the border style is 'none' or 'hidden'
你可以see,它说的是Percentages: N/A.
非脚本解决方案
您可以使用包装元素模拟百分比边框,您可以执行以下操作:
- 将包装元素的
background-color
设置为所需的边框 colored颜色
- 以百分比形式设置包装器元素的
padding
(因为它们是受支持的)
- 将元素
background-color
设置为白色(或任何需要的值)
这会以某种方式模拟您的百分比边界.使用该技术的具有25%宽度侧borders的元件的Here's an example.
示例中使用的HTML
.faux-borders {
background-color: #f00;
padding: 1px 25%; /* set padding to simulate border */
}
.content {
background-color: #fff;
}
<div class="faux-borders">
<div class="content">
This is the element to have percentage borders.
</div>
</div>
Issue:您必须意识到,当您的元素应用了一些复杂的背景时,这将变得复杂得多……特别是如果该背景继承自祖先DOM层次 struct .但是如果你的UI足够简单,你可以这样做.
脚本化解决方案
@BoltClock mentioned scripted solution,其中您可以编程地根据元素大小计算边框宽度.
使用jQuery编写非常简单的脚本.
var el = $(".content");
var w = el.width() / 4 | 0; // calculate & trim decimals
el.css("border-width", "1px " + w + "px");
.content { border: 1px solid #f00; }
<div class="content">
This is the element to have percentage borders.
</div>
但你必须意识到,每次你的container size changes(即调整浏览器窗口大小)时,你将不得不使用adjust的边框宽度.我使用包装器元素的第一个解决方法看起来要简单得多,因为在这些情况下它会自动调整宽度.
脚本化解决方案的积极方面是,它不会受到我以前的非脚本化解决方案中提到的背景问题的影响.