如何用HTML和CSS实现带hr分割的圆形?解决桌面端hr溢出问题
HR标签分割圆形的跨端兼容问题
我需要实现如图所示的HR标签将圆形一分为二的效果,已编写对应HTML和CSS代码,该效果在Android端显示正常,但桌面端HR标签会超出圆形范围并跑到圆形顶部,求正确实现方式及兼容解决方案。

原代码
CSS
#circle { border : 5px solid red; width : 40%; box-shadow : 0 0 20px red, inset 0 0 20px red; aspect-ratio : 1/1; border-radius : 50%; text-align : center; font-size : large; } #circle > div { font-size : 24px; color : white; text-shadow : 0 0 10px #0fa; } #circle > hr { background : red; border : 2px solid red; box-shadow : 0 0 20px red, inset 0 0 20px red; } #circle > span { color : white; text-shadow : 0 0 10px #0fa; }
HTML
<div class="circle" id="circle"> <br> <div id="result1" ></div> <hr> <span id="result2"></span> </div>
问题原因
桌面端浏览器默认给HR标签设置了margin、padding等默认样式,加上用<br>标签控制间距的方式不稳定,不同浏览器解析差异导致HR位置偏移且超出圆形边界。
修复方案
修改后的代码
CSS
#circle { border : 5px solid red; width : 40%; box-shadow : 0 0 20px red, inset 0 0 20px red; aspect-ratio : 1/1; border-radius : 50%; text-align : center; font-size : large; overflow : hidden; /* 隐藏超出圆形的内容 */ display : flex; /* 用Flex布局实现垂直分布 */ flex-direction: column; justify-content: center; gap: 1rem; /* 控制上下内容的间距 */ } #circle > div { font-size : 24px; color : white; text-shadow : 0 0 10px #0fa; } #circle > hr { background : red; border : none; /* 重置HR默认边框 */ height : 4px; /* 自定义横线高度 */ box-shadow : 0 0 20px red, inset 0 0 20px red; margin : 0 10%; /* 控制横线左右边距,避免贴满圆形 */ } #circle > span { color : white; text-shadow : 0 0 10px #0fa; }
HTML
<div class="circle" id="circle"> <div id="result1"></div> <hr> <span id="result2"></span> </div>
关键改动说明
overflow: hidden:强制圆形容器内的所有元素都被圆角裁剪,不会超出边界- Flex布局:替代
<br>的硬间距,实现上下内容的垂直居中分布,跨浏览器一致性更强 - 重置HR样式:清除默认的border和margin,自定义高度和左右边距,让横线在圆形内居中显示,避免位置偏移
内容的提问来源于stack exchange,提问作者Kumara Swamy S
相关产品推荐
相关产品推荐

