我正在尝试制作带有文字的圆圈。问题是当字体变大时......文本与圆圈重叠。我该如何解决这个问题?
.circle {
display: inline-block;
font-size: 42px;
}
.circle label {
cursor:pointer;
height: 200px;
width: 200px;
display: table-cell;
text-align: center;
vertical-align: middle;
border-radius: 50%;
background: yellow;
}
label input[type="checkbox"] {
display:none;
}
input[type="checkbox"]:checked + span {
color: #fff;
}
最佳答案
在根据内容调整 div 大小的同时保持圆形(不是椭圆形/椭圆形)根本不是一件容易的事。
有一种技术使用具有 100% 宽度和 100% 底边距的绝对定位伪元素来保持圆圈……一个圆圈。
它依赖于 padding-top 和 padding-bottom 的百分比是根据宽度而不是大多数人期望的高度来计算的事实,以防止无限循环。听起来违反直觉,但它确实有效。
还有实际内容不是圆高度的 100% 的问题(包装器也不是,因为圆是绝对定位的),因此将内容居中也很有挑战性。再一次,在 padding-top 上使用 % 以便根据宽度 + 负变换计算它:translateY 就可以了。
最后但并非最不重要的一点是,将单词保持在不同的行上是 width: min-content 的一项工作。
所有这些,结果是:
body{
/*just to display circles inline and centered*/
display:flex;
align-items:center;
flex-wrap: wrap;
}
.circle{
padding:1em;
}
.inner{
/*centers the content*/
padding:100% 20px 0 20px;
transform:translateY(-50%);
/*sets the width as the biggest word*/
width:min-content;
/*styling*/
text-align:center; color:white; font-weight:bold; font-family:sans-serif;
/*sets the label as inline-block, so it doesn't take 100% width*/
display:inline-block;
/*prevents clicks outside the circle from switching the checkbox*/
pointer-events:none;
}
.inner::before{
content:"";
position:absolute;
/*adjust for the padding + translateY on the element*/
top:50%; left:0;
/*sets the width as 100% of the element*/
width:100%;
/*sets the padding-bottom (and therefore, the height) as 100% the width of the element*/
padding-bottom:100%;
/*styling*/
background-color:steelblue;
border-radius:50%;
/*puts it behind the content*/
z-index:-1;
/*resets the pointer-events so clicking on the circle affects the checkbox */
pointer-events:auto;
cursor:pointer;
}
<input type="checkbox" id="check1">
<div class="circle">
<label for="check1" class="inner">Really biiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiig circle</label>
</div>
<input type="checkbox" id="check2">
<div class="circle">
<label for="check2" class="inner">small circle</label>
</div>
请注意,我已将标签调整为 .inner 标签,但将指针事件设置为无,然后在伪元素上将其重置,以防止在圆圈外(但在框内)的点击切换复选框
关于html - 圆圈css3问题中的中心文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48572860/