HTML5 stretch to 16:9 in Landscape, 9:16 in Portrait mode

I have a web game that needs to be presented in 16:9 in landscape mode (PCs), 9:16 mode in mobile phones, no matter the screen size.

So far, using stretch mode works nicely in landscape in PC and also in portrait in those phones that are close to 9:16. But on an ipad in portrait mode for instance things just don’t work because of its 4:3 aspect.

What I need is to make it so the game in portrait is always 9:16 (but 16:9 in landscape!), no matter the screen size - so the game will be narrower in screens like iPad’s, but will keep its looks. Don’t worry about content, I need the container.

My wild guess is that I have to combine stretch mode with proper CSS, but I’ve been trying o use flex, grid and undust my poor CSS knowledge to no avail.

Any clue how can this be done?

You could experiment with combining aspect-ratio and orientation media queries.

Something like this:

@media (orientation: landscape) {
	canvas {
		aspect-ratio: 16 / 9;
		height: auto !important;
	}
	.canvas-app-container {
		aspect-ratio: 16 / 9;
		height: auto !important;
	}
}

@media (orientation: portrait) {
	canvas {
		aspect-ratio: 9 / 16;
		height: auto !important;
	}
	.canvas-app-container {
		aspect-ratio: 9 / 16;
		margin-top: 0px !important;
		height: auto !important;
	}
}

4 Likes

Thank you! I think I already tried that and didn’t work, but I probably messed up somewhere. I managed something yesterday with a bit of ugly JavaScript code and adding an outer container in flex display.

Will try your solution today and share mine!