12

Is it possible to make a square div with css based on its height in pixels?

This question is similar to this one (marked as duplicate), but in this case I want height to be set in pixel or any unit.

When based on width, there is a simple solution :

.mydiv {
    height: 0;
    padding-bottom: 100%;
}

But here 'height follows width'. I'm looking for solution where 'width follows height'. So if I would set height to 300px, width would follow it.

For now I'm doing it using javascript, updating on window resize. But I would like to find a CSS solution, thats why I'm not looking for a javascript solution

Here is a playground

Community
  • 1
  • 1
Adam Pietrasiak
  • 12,773
  • 9
  • 78
  • 91

1 Answers1

0

You could use the new viewport size units

JSfiddle

CSS

html,body {
    height: 100%;
    margin: 0;
}
div {
    background: red;
    height: 100vh;
    max-width:100vh;
    box-sizing: border-box;
}

Support is effectively IE9 and up

Paulie_D
  • 107,962
  • 13
  • 142
  • 161
  • 8
    That's not answering his question. As far as I know, he wanted to know if it is possible to make the height influence the width in a specific way. Which, by the way, is something I'd also love to know. – CunningFatalist Jul 21 '14 at 14:01
  • @sb this is the answer to the question if you look at the demo, the aspect ratio of the div is maintained according to it's height. – web-tiki Jul 21 '14 at 14:03
  • 3
    But only for this very specific example. Edit: By the way, I'm not trying to be mean or anything. I'm just saying that the answer I'm hoping for (and I guess others too) is still out there :) – CunningFatalist Jul 21 '14 at 14:03
  • @sb. so... it answers the question... – web-tiki Jul 21 '14 at 14:04
  • 1
    Don't think so! I doubt that he's trying to fill a square viewport like this. – CunningFatalist Jul 21 '14 at 14:05
  • 2
    The problem here is that vh is relative to screen (resolution) size, so it would be hard (and requireing js) to make like height: 150px; At the end - I think this solution is working indeed, but vh unit makes it not so useful (for example comparing to solution based on width) – Adam Pietrasiak Jul 21 '14 at 14:05
  • I've edited question so I want height to be set in pixels or any unit that makes this answer not matching. Thanks anyway. – Adam Pietrasiak Jul 21 '14 at 14:24