Responsive, Centered Square Div that Resizes Based on Height in Landscape – CSS

This particular project was requested by @sanjaypoyzer. He wanted to elaborate on our trick to maintain aspect ratio for an element with CSS. His goal was to have a div, WITH content, that would maintain its square shape while still being responsive. Easy enough to do if you want the square to respond relative to the width of the browser window. But he wanted to take it a step further. If the viewing device is in LANDSCAPE mode, he wanted the element to resize relative to the HEIGHT of the browser, which is a much trickier thing to do.

So I found a solution that should work well on mobile devices. It does, however, break down a bit on a desktop version IF users are going to be resizing their browser while viewing it. It relies on a little hack utilizing a square image to resize the div. Positioning was also quite tricky to accomplish. Vertical centering is typically a tricky thing in CSS, but it can be done, even in this situation. So let’s take a look at our HTML we are going to try and work with.

We want to have our “main” element be centered and square, and have the following h2 and paragraph remain with in it. Again, as long as the browser isn’t actively being resized, this should work fairly well. Let’s take a look at where the real magic happens – the CSS.

View the example page of this in action here.

There is actually quite a lot to it. But you see that if we go into landscape mode (the browser is wider than it is tall), we get a different set of CSS. Those are the rules used to make it resize relative to height. And it works pretty well when the browser first opens. The problem is that, at least in Chrome, which I’m using, the MAIN div does not resize WIDTH dynamically as you resize the browser window, even though it will if you refresh after you’ve resized it. But on mobile devices, where you can’t really resize the browser typically, this may work perfectly.

My suggestion to anyone wanting to use it, would be to set up a simple mobile redirect to this page, while leaving desktop users on a page that has our div only resize based on browser width, not height. I think it makes a little more sense to leave it that way on the computer, and then you don’t really have to worry about the failure to resize dynamically when you adjust your browser window.

That’s pretty much all there is to it! I hope someone else can come along and figure out a better way to do this, perhaps one that would work better on a desktop. Until then, we have this! Happy coding!

About Brian Johnson

Brian Johnson is a website developer and designer living in Minneapolis, Minnesota with a passion for code and WordPress. He spends his days building WordPress websites for small businesses, developing new code with the online community, and living life.

Leave a Reply

Your email address will not be published. Required fields are marked *