LoginSignup
6
2

More than 5 years have passed since last update.

CSS3で角丸のボーダーをアニメーションさせる

Posted at

CSS3で角丸のボーダーをアニメーションさせる

CSSでミシンっぽい表現のアニメーションを作ってみたかったのでやってみました。
ミシン感あるかどうかは諸説ありですが、なんとなくできました。

image.png

動くサンプルはこちらです。
jsfiddle
オレンジの領域をホバーするとアニメーションが開始します。

検索ではボーダーシャドウを使ってやる方法は多くヒットしたのですが、
角を丸くすることができなさそうだったので試してみました。

beforeとafter疑似要素を使って、ボーダーの上に色を乗せて隠しておき、
アニメーションで隠している部分の位置とサイズを調整して徐々に表示していく感じです。

コードは次のとおりです。

HTML
<div class="draw">
  <div class="border">
    <div class="content">
      Rounded border animation
    </div>
  </div>
</div>

CSSはSassで記述しています。

CSS(SCSS)
$speed: 2s;
$base-color: orange;
$color: white;

.content {
  z-index: 2;
  position: relative;
  display: block;
  padding: 20px;
  color: $color;
  text-shadow: -1px -1px #d48020;

}

.draw {
  width: 300px;
  height: 70px;

  margin-top: 100px;
  margin-left: 100px;

  top: calc(50% - 50px);

  background: $base-color;
  border: 0;
  box-sizing: border-box;

  border: 2px dashed $color;
  border-radius: 10px;
  font-size: inherit;
  font-weight: bold;
  position: relative;
  vertical-align: middle;

  &::before {
    display: block;
    position: absolute;
    background-color: $base-color;
    content: '';
    box-shadow: 0 0 0 4px #FBA848, 2px 1px 6px 4px rgba(10, 10, 0, 0.5);

    top: -10px;
    left: -10px;
    width: calc(100% + 20px);
    height: calc(100% + 20px);
    border-radius: 10px;
    z-index: -1;
  }
}

.border {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;

  &::before {
    display: block;
    position: absolute;
    background-color: $base-color;
    content: '';

    top: -5px;
    left: -5px;
    width: calc(100% + 10px);
    height: calc(100% + 10px);
    border-radius: 10px;
  }

  &::after {
    display: block;
    position: absolute;
    background-color: $base-color;
    content: '';

    top: 0px;
    left: -5px;
    width: calc(100% + 5px);
    height: calc(100% + 5px);

    border-radius: 10px;
  }

  &:hover::before {
    top: calc(100% + 5px);
    left: 100%;
    width: 5px;
    height: 0;
  }

  &:hover::after {
    left: -5px;
    width: 5px;
    height: 0;
  }

  &:hover::before {
    transition:
      width $speed ease-out,
      left $speed ease-out,
      height $speed ease-out $speed,
      top $speed ease-out $speed;
  }

  &:hover::after {
    transition:
      width $speed ease-out $speed * 2,
      height $speed ease-out $speed * 3;
  }
}
6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2