LoginSignup
2
0

More than 5 years have passed since last update.

jQueryを使ってdivタグをレスポンシブな正方形にする方法

Last updated at Posted at 2019-03-04

動作環境

  • HTML 5
  • CSS 3
  • jQuery 3.3.1

論よりコード

HTML

bodyタグ
<body>
    <div class="main">
        <div id="target" class="square">正方形1</div>
        <div class="square">正方形2</div>
        <div class="square">正方形3</div>
        <div class="square">正方形4</div>
    </div>
</body>

今回は4つの正方形を描画

JavaScript

scriptタグ
<script src="https://ajax.googleapis.com/ajax/libs/jquery/x.x.x/jquery.min.js"></script>
<script>
    // 最初のロード時とリサイズ時に発火
    $(window).on("load resize", function() {
        // id="target"のwidthを取得
        var width = $("#target").width();
        // class="square"のheightに設定
        $(".square").css({"height": width});
    });
</script>

jQueryの呼び出しを忘れずに!!

CSS

styleタグ
<style>
    .square {
        background-color: #ccc;
        display: inline-block;
        margin: 0;
        padding: 0;
        width: 20%;
    }
</style>

背景を灰色に設定し、横に4つ並べている

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