【问题标题】:Unwanted Space in Border Transition边界过渡中不需要的空间
【发布时间】:2016-12-06 07:14:17
【问题描述】:

我在 CSS 中为一个 div 做了一个边框过渡,它基本上使边框以时钟工作的方式变得可见。

Here it is

将鼠标悬停在灰色矩形上即可查看。

由于网站要求我提供以下代码,请查看链接。

<div class="outerBox"></div>

然而,正如您在钢笔中看到的那样,灰色矩形的边缘和边框之间有空隙,并且两端没有正确相遇.

关于为什么会发生这种情况的任何想法?

更新

其实,找到解决办法了。

【问题讨论】:

  • 您使用哪种浏览器?在 Chrome 中看起来很完美......
  • @TheodoreK。我实际上发现了问题并更新了codepen。它与使用 box-sizing 属性有关。
  • 好,记住你也可以在stackoverflow中回答你自己的问题。
  • @TheodoreK。是的,刚刚做了,感谢您的光临,不胜感激!

标签: css border css-transitions pseudo-element


【解决方案1】:

我发现问题与 边框的宽度改变 div 元素的 box-size 的方式有关。

基本上,将边框设置为 2px 就是为 div 元素添加 2px 的宽度(我相信在每一边),从而导致空间和未满足的末端。

解决方案是添加声明

box-sizing: border-box;

到 ::before 和 ::after 伪元素(为了安全起见,我将它添加到 div 元素)然后 div 元素的宽度不再受边框宽度的影响。强>

如果您单击我的问题中的链接,您会看到边框现在很好地包围了矩形。

要查看之前的状态,只需注释掉 box-sizing:border-box;声明实例。

【讨论】:

    【解决方案2】:

    具有多种背景的更简单的解决方案:

    * {
      box-sizing: border-box;
    }
    
    body {
      background: silver;
    }
    
    .box {
      background-color: white;
      height: 10em;
      margin: 2em auto;
      width: 10em;
    }
    .box:hover {
      animation: border 1s linear forwards;
      background-image: linear-gradient(to left, red, red), linear-gradient(to left, red, red), linear-gradient(to left, red, red), linear-gradient(to left, red, red);
      background-position: top left, top right, bottom right, bottom left;
      background-repeat: no-repeat, no-repeat, no-repeat, no-repeat;
    }
    
    @keyframes border {
      0% {
        background-size: 0% 4px, 4px 0%, 0% 4px, 4px 0%;
      }
      25% {
        background-size: 100% 4px, 4px 0%, 0% 4px, 4px 0%;
      }
      50% {
        background-size: 100% 4px, 4px 100%, 0% 4px, 4px 0%;
      }
      75% {
        background-size: 100% 4px, 4px 100%, 100% 4px, 4px 0%;
      }
      100% {
        background-size: 100% 4px, 4px 100%, 100% 4px, 4px 100%;
      }
    }
    &lt;div class="box"&gt;&lt;/div&gt;

    【讨论】:

    • 经过一些实验,我实际上将这个关键帧方法与我已有的方法结合起来:codepen.io/edsonmendieta/pen/ENLwEw 它使用了两个关键帧,但我更喜欢它,因为它看起来更具可读性/对我来说合乎逻辑,我更喜欢使用 ::before 和 ::after。
    • 当然。很高兴看到keyframes ;)
    猜你喜欢
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多