CSS square based on height [duplicate]
Asked Answered
D

1

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

Defilade answered 21/7, 2014 at 13:43 Comment(0)
T
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

Tourane answered 21/7, 2014 at 13:55 Comment(7)
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.Fess
@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.Highsounding
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 :)Fess
@sb. so... it answers the question...Highsounding
Don't think so! I doubt that he's trying to fill a square viewport like this.Fess
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)Defilade
I've edited question so I want height to be set in pixels or any unit that makes this answer not matching. Thanks anyway.Defilade

© 2022 - 2024 — McMap. All rights reserved.