0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

こんにちは!
今回はCSS編になります。

高さを横幅の長さに応じて、高さを揃えたい時ありますよね?
つまり、要素を正方形に表示したい時です。

aspect-ratio

これを使えばOK。

<section>
    <div
      style="width: 30%; aspect-ratio: 1; background-color: aquamarine"
    >
    横幅30% x 高さは横幅と同じ
    </div>
</section>

JavaScript版

リサイズイベントを設定して、正方形にしたい要素の横幅を取得して、そのまま高さに設定する方法です。

<script>
    window.addEventListener('resize', function() {
        const square = document.getElementById('正方形にしたい要素')
        const width = square.offsetWidth
        square.style.height = width + 'px'
    });

    // ページがロードされた直後にリサイズイベントを手動で発生させる
    window.dispatchEvent(new Event('resize'))
</script>

備忘録 😁

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?