繁体   English   中英

CSS圆圈没有使用固定的宽度和高度

[英]CSS circle without using fixed width and height

我想在圆圈内显示通知计数,但我不希望它具有固定的宽度,因此当圆圈内有更大的数字/文本时,圆圈可以展开。

 .circle { height: 20px; width: 20px; line-height: 20px; border-radius: 50%; background-color: red; color: white; text-align: center; } 
 <div class="circle">5</div> <br> <div class="circle">102</div> 

请参阅此仅CSS解决方案。 为1位数设置相同的min-widthmin-height值。 使用伪元素进行垂直对齐并保持方形。 border-radius适用于圆的容器。

 .circle { display: inline-block; border-radius: 50%; min-width: 20px; min-height: 20px; padding: 5px; background: red; color: white; text-align: center; line-height: 1; box-sizing: content-box; white-space: nowrap; } .circle:before { content: ""; display: inline-block; vertical-align: middle; padding-top: 100%; height: 0; } .circle span { display: inline-block; vertical-align: middle; } 
 <div class="circle"><span>8</span></div> <div class="circle"><span>64</span></div> <div class="circle"><span>512</span></div> <div class="circle"><span>4096</span></div> 

这太苛刻了,但它似乎检查了所有主流浏览器的最新版本,所以无论如何我都会发布它。 基本原则是基于百分比的填充(甚至顶部和底部填充)相对于父级的宽度。 将其设置为100% ,宽度和高度为0理论上意味着元素的高度始终等于宽度。 将它与伪元素结合起来甚至不需要更改标记。 我使用flexbox来纠正内容的居中。 它似乎适用于我测试它的浏览器,但这肯定取决于最新版本,因为它使用flexboxdisplay:table 我还必须添加一个min-width以确保它不会因为内容太少而变形。

 .circle { background-color: red; color: white; text-align: center; position: relative; border-radius: 50%; min-width: 1.25em; display: inline-flex; align-items: center; justify-content: center; } .circle:after { content: ''; padding-top: 100%; display:table; } 
 <div class="circle">5</div> <br> <div class="circle">102</div> <br> <div class="circle">4298347918</div> 

简单的CSS适用于几乎可以运行的圆圈:

.circle {
    position: relative;
    border-radius: 50%;
    width: 100%;
    height: auto;
    padding-top: 100%;
}

技巧是填充顶部是根据宽度计算的,因此您可以将其用于makinh高度等于宽度

尝试使用border-radius:50%并设置max-width和height

是一个快速示例,您可以在其中看到如何使用css和js动态维护一个圆。

正如Jagjit Singh在这里指出的那样,你可以使用border-radius: 50%;来实现一个圆border-radius: 50%; 而不是固定的像素值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM