使用CSS计算较小宽度的边框半径

时间:2019-06-06 02:35:21

标签: javascript html css

我想为进度创建一个滑块

如果说是1%,如何计算边界半径的正确px /%?

%很大时看起来不错

<div style="background: grey; height: 25px; border-radius: 12.5px; width: 100%">
  <div style="background: green; height: 25px; border-radius: 12.5px; width: 15%" />
</div>

当它小到1%时看起来像这样

<div style="background: grey; height: 25px; border-radius: 12.5px; width: 100%">
  <div style="background: green; height: 25px; border-radius: 12.5px; width: 1%" />
</div>

4 个答案:

答案 0 :(得分:2)

尝试添加:

overflow: hidden;

用于绿色填充物。它将隐藏在容器内。您试图做的几乎是不可能的。您能想象在border-radius< 2px的元素上添加width吗?

<div style="background: grey; 
            height: 25px; 
            border-radius: 12.5px; 
            width: 100%; 
            overflow: hidden;">
  <div style="background: green; 
              height: 25px; 
              border-radius: 12.5px; 
              width: 1%" />
</div>

答案 1 :(得分:0)

如果您想完全保留进度条的半径,则可以尝试克隆与进度条容器相同的元素并设置其left

此示例正在使用Javascript,或者您只能通过编辑其left来使用纯CSS。

请查看这是否也是您的另一个好选择。

set_progress(2); // percentage of progress

function set_progress(p) {
  $('.progress-container span').css('left', (p-100)+'%');
}
.progress-container {
  position: relative;
  display: block;
  width: 100%;
  height: 24px;
  background-color: #555;
  border-radius: 12px;
  overflow: hidden;
}
.progress-container > span {
  position: absolute;
  display: block;
  top: 0;
  left: -100%;
  width: 100%;
  height: 24px;
  background-color: #0c0;
  border-radius: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="progress-container">
  <span></span>
</div>

答案 2 :(得分:0)

由于失去了绿色进度元素的width,因此失去了边界半径。

相反,如果将绿色div设置为相同的100%宽度,则可以通过使用CSS变换将绿色div移到左侧来表示进度。

transform: translateX(-90%); 

这是您要更改以更新进度的值,请使用反值,因此-90%实际上是进度的10%(100-10 = 90),依此类推。

在外部div上使用overflow: hidden;隐藏多余的绿色。

.progress-bar {
  overflow: hidden; /* hide the green that overflows */
  background: grey;
  height: 25px;
  width: 100%;
  border-radius: 12.5px;
}

.progress {
  display: block;
  background: green;
  height: 100%;
  width: 100%; /* same width as outer div */
  border-radius: 12.5px;
  transform: translateX(-90%); /* this is the value you want to change to update the progress, use inverse value, so -90% is really 10% of progress (100 - 10 = 90) */
}
<div class="progress-bar">
  <div class="progress"></div>
</div>

答案 3 :(得分:0)

我认为1%的比例看起来很小。只需将overflow: hidden添加到您的父div,那么效果会更好。

<div style="overflow:hidden; background: grey; height: 25px; border-radius: 12.5px; width: 100%">
  <div style="background: green; height: 25px; border-radius: 12.5px; width: 1%" />
</div>

相关问题