是否可以仅使用 HTML5 / CSS3 创建一个圆形,其边框仅围绕圆形一部分?如果没有,我可以使用什么技术来实现这种效果?我更喜欢使用纯 DOM 元素,但如果必须的话,我可以在画布上绘图或旋转 SVG。
2023年解决方案
这个方法不需要 JS,不需要额外的元素,甚至不需要任何伪元素,只需要少量的 CSS 声明。如果元素具有(半)透明,它也适用background
除了这部分border
.
它使用两层mask
,其中一个是conic-gradient
它创建了一个可见的饼图选择,其大小相对于border-box
第二个是简单的全覆盖层,仅限于padding-box
.
首先,我们将元素设为圆形(任意width
, an aspect-ratio
of 1
and a border-radius
set to 50%
)并给它一个border
.
然后,我们设置一个mask
那是一个conic-gradient()
,相对于border-box
,覆盖百分比--p
我们的元素(默认从 12 点钟开始顺时针方向)。
除此之外mask
层,我们设置一个仅限于的全覆盖层padding-box
.
.circular-progress {
border: solid 1.5em hotpink;
width: 50vmin;
aspect-ratio: 1;
border-radius: 50%;
background: hsla(180, 100%, 50%, .5);
--mask:
linear-gradient(red, red) padding-box,
conic-gradient(red var(--p, 17%), transparent 0%) border-box;
-webkit-mask: var(--mask);
mask: var(--mask)
}
/* just to make it obvious it works with semitrasparent background */
body {
background:
url(https://images.unsplash.com/photo-1693483923875-cdd9ef4a8046?w=800)
50%/ cover
}
<div class='circular-progress'></div>
如果我们想要动画化,我们还需要注册--p
.
@property --p {
syntax: '<percentage>';
initial-value: 0%;
inherits: true
}
.circular-progress {
border: solid 1.5em hotpink;
width: 50vmin;
aspect-ratio: 1;
border-radius: 50%;
background: hsla(180, 100%, 50%, .5);
--mask:
linear-gradient(red, red) padding-box,
conic-gradient(red var(--p), transparent 0%) border-box;
-webkit-mask: var(--mask);
mask: var(--mask);
animation: p 4s linear infinite
}
@keyframes p { to { --p: 100% } }
/* just to make it obvious it works with semitrasparent background */
body {
background:
url(https://images.unsplash.com/photo-1693483923875-cdd9ef4a8046?w=800)
50%/ cover
}
<div class='circular-progress'></div>
Chromium 浏览器和 Safari 都支持以这种方式注册自定义属性,以便为它们设置动画,并且 Firefox Nightly 也即将推出。
2012 年的原始答案(由于网络历史记录原因而保留)
是的,这是可能的 - 请看这个:
.circle {
position: relative;
margin: 7em auto;
width: 16em;
height: 16em;
border-radius: 50%;
background: lightblue;
}
.arc {
overflow: hidden;
position: absolute;
/* make sure top & left values are - the width of the border */
/* the bottom right corner is the centre of the parent circle */
top: -1em;
right: 50%;
bottom: 50%;
left: -1em;
/* the transform origin is the bottom right corner */
transform-origin: 100% 100%;
/* rotate by any angle */
/* the skew angle is 90deg - the angle you want for the arc */
transform: rotate(45deg) skewX(30deg);
}
.arc:before {
box-sizing: border-box;
display: block;
border: solid 1em navy;
width: 200%;
height: 200%;
border-radius: 50%;
transform: skewX(-30deg);
content: '';
}
<div class='circle'>
<div class='arc'></div>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)