求助:如何用CSS实现目标样式的半月形(附现有代码)
问题描述
我尝试制作下图所示的半月形样式:
目前写出了如下代码,但实现效果与目标图不符,需要技术帮助:
现有代码
CSS
.meia-lua { width: 50px; height: 40px; background-color: #000; border-radius: 100% 100% 50% 50%; position: relative; overflow: hidden; display: flex; align-items: center; justify-content: center; font-size: 18px; font-weight: bold; margin-left: auto; margin-right: auto; color: #fff; text-align: center; line-height: 40px; }
HTML
<div class="meia-lua">1</div>
解决方案
你当前代码的border-radius设置会让元素上下边缘是半圆、左右是圆角,和目标半月形不符。下面提供两种适配目标效果的实现方式:
方式一:直接调整border-radius(适合平直边缘的半月)
如果目标是左侧半圆、右侧平直的样式,修改border-radius为对角半圆即可:
.meia-lua { width: 50px; height: 40px; background-color: #000; /* 左侧上下为半圆,右侧无圆角 */ border-radius: 100% 0 0 100%; display: flex; align-items: center; justify-content: center; font-size: 18px; font-weight: bold; margin: 0 auto; color: #fff; }
若需要右侧半圆的样式,将border-radius改为0 100% 100% 0即可。
方式二:伪元素遮挡(适合弧形缺口的半月)
如果目标是类似弦月的弧形缺口样式,可通过伪元素覆盖部分圆形区域实现:
.meia-lua { width: 50px; height: 50px; background-color: #000; border-radius: 50%; position: relative; display: flex; align-items: center; justify-content: center; font-size: 18px; font-weight: bold; margin: 0 auto; color: #fff; } /* 伪元素遮挡右侧区域,形成半月 */ .meia-lua::after { content: ""; position: absolute; width: 100%; height: 100%; /* 背景色需和页面背景一致 */ background-color: #ffffff; left: 50%; border-radius: 0 50% 50% 0; }
调整伪元素的left/right属性或宽度,可灵活控制缺口的位置和大小。
内容的提问来源于stack exchange,提问作者Patrique
相关产品推荐
相关产品推荐

