1

What I try to make is square that change size with the size of the screen.

So I have the width set to 25%. How do I make sure that the height keeps the same length in px as the width?

Thanks in advance.

user3428833
  • 103
  • 1
  • 9

3 Answers3

6

You could use top/bottom padding property in percentage, to achieve the result.

Example Here.

.box {
    width: 25%;
    padding-bottom: 25%;
}

A percentage value on top/bottom padding or margins is relative to the width of the box's containing block.

8.4 Padding properties: 'padding-top', 'padding-right', 'padding-bottom', 'padding-left', and 'padding'

<percentage> The percentage is calculated with respect to the width of the generated box's containing block, even for 'padding-top' and 'padding-bottom'.


Adding the content

Since the the height of the box grows by adding content, we could wrap the content by an element .wrapper and position that absolutely relative to the box, and then use top, right, left and bottom properties to fill the entire space of the box.

Example Here

<div class="box">
  <div class="wrapper">
    <!-- content goes here... -->
  </div>
</div>
.box {
  width: 25%;
  position: relative;
}

.box:after {
  content: "";
  display: block;
  padding-top: 100%; /*  1:1 square */
}

.box > .wrapper {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
}

For further information you could refer my answer here (Responsive Container section).

Community
  • 1
  • 1
Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
0

you may set the width value as a percentage, then grab it with jquery then let it to be the height value. see this

var box = $(".box");
var width = box.css("width");
box.css("height", width);

http://jsfiddle.net/DPYcg/1/

Ahmedskaya
  • 389
  • 1
  • 10
0

To be able to add contents, you may use pseudo element and floats behavior : http://codepen.io/anon/pen/fklAr/

div {
  width:25%;
  background:red;
  margin:auto;
}
div:before, div:after {
  content:'';
}
div:before {
  float:left;
  padding-top:100%;
}
div:after {
  display:block;
  clear:both;
}

maybe a duplicate if you want to center content : Center content in the middle of div container

Community
  • 1
  • 1
G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129