首页 > 解决方案 > div的CSS边框半径:首次加载时伪元素渲染错误

问题描述

我一直在尝试通过使用具有匹配边框半径的 div:after 伪元素来更改图像颜色叠加层。

https://jsbin.com/konopak/1/edit?html,输出

您会注意到在第一次加载时背景颜色是一个实心正方形,但如果您移动框架或更改页面上的任何元素,它会正确呈现它。有没有办法让它在第一次加载时正确渲染?为什么会这样?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>

  <style>
    img {
      max-width: 100%;
      height: auto;
      border-radius: 90px;
    }

    .hero-image {
      position: relative;
      max-width: 200px;
      display: flex;
      background-color: #ff000050;
      /* border-radius: 90px; */
    }

    .hero-image:after {
      position: absolute;
      height: 100%;
      width: 100%;
      background-color: inherit;
      top: 0;
      left: 0;
      display: block;
      content: "";
      border-radius: 90px;
    }
  </style>
</head>
<body>
<label id="color-label" style="background-color: #ff0000; height: 18px; width: 18px; border-radius: 10px; cursor: crosshair;">
  <input id="color-tag" type="color" value="#ff0000" style="visibility: hidden;">
</label>

<div class="hero-image">
  <img src="https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=400&w=400" id="cat" alt=""/>
</div>

<script>
  const label = document.getElementById('color-label');
  document.getElementById('color-tag').addEventListener('change', function () {
    label.style.backgroundColor = this.value;
    let imgDom = document.querySelector('.hero-image');
    imgDom.style.backgroundColor = this.value + '40';
    // imgDom[0].style.backgroundColor = this.value;
  });
</script>

</body>
</html>

标签: javascripthtmlcss

解决方案


您可以简单地添加overflow: hidden;到父级并删除其他border-radius属性,display: flex这会导致 safari 中的显示问题。

我建议按照以下内容进行一些更新,以帮助图像缩放:

 img {
      width: 100%;
      height: auto;
    }

    .hero-image {
      position: relative;
      max-width: 200px;
      max-height: 200px;
      background-color: #ff000050;
      border-radius: 90px;
      overflow: hidden;
    }

    .hero-image:after {
      position: absolute;
      height: 100%;
      width: 100%;
      background-color: inherit;
      top: 0;
      left: 0;
      display: block;
      content: "";
    }

容器父级的半径 + 溢出应该是所有需要的,额外的子属性是多余的。

JSbin 更新


推荐阅读