3

I need a <div> with a height in percent and a width so that it is a square. So the width has to refer to the height.

CSS:

#square {
    height: 100%;
    width: "100% of height of this div";
}  

HTML:

<div id="square"></div>  

I've seen a solution with the padding-top property (example), but it only works with a given height. Another way is a JavaScript/jQuery solution like this, but I would prefer a CSS only solution.

Is there a nice way of doing this (without a blank square <img> or something)? Maybe equal to padding-top? I've tried padding-right already but it does not work.

Community
  • 1
  • 1
THWBM
  • 101
  • 1
  • 7
  • 1
    @TylerH My question is not a dublicate of [this](http://stackoverflow.com/questions/31013181/how-to-force-a-responsive-element-to-retain-its-aspect-ratio). My question is about a `width` refering to the `height` and not a `height` refering to the `width`. If I see it right the answer of the post you linked to does not work for my problem. – THWBM Jul 30 '15 at 21:04
  • There are multiple answers to that question, the second of which is the same implementation as the two answers here. – TylerH Jul 30 '15 at 21:08
  • @TyleH I've treid to do it like it is said in the answer you linked to or in the answers of this question but it does not work perfectly. If I've got a `height` relating to the complete screen height it is hard to calculate the correct size of a square `
    ` inside another `
    ` element with persentage size. It would be great if there was a solution like `padding-top` as I mentioned it in the end of my question.
    – THWBM Jul 31 '15 at 18:21

2 Answers2

4

Have you tried using the viewport widths? They have pretty good browser support. I would also suggest using a class rather than ID, this reduces CSS specificity and enables you to re-use the style...

<div class="square"></div>

.square {
    height: 100vh;
    width: 100vh;
}
steffcarrington
  • 404
  • 3
  • 13
2

Here you have:

HTML:

<div class="square">
    <h1>This is a Square</h1>
</div>

CSS:

.square {
    background: #000;
    width: 50vw;
    height: 50vw;
}
.square h1 {
    color: #fff;
}
arodriguezdonaire
  • 5,396
  • 1
  • 26
  • 50