Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

動作環境

  • 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つ並べている

piyox2
Meiji Univ. FMS 4th
https://twitter.com/fms_2905
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした