Antoine BERNIER
Sep 12, 2018 Β· 1 min read

Great trick! πŸ‘

Following your idea, we could also generate the SVG as CSS pseudo-element using image content and SVG data-URIs, ie:

.aspectRatioSizer:before {
content:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 7 2"></svg>');
}

with minimum markup (no more `<svg>` tag needed):

<div class="aspectRatioSizer">
<div>
Content goes here
</div>
</div>

No more ratio value into HTML, but CSS πŸ˜‰

Forking your pen, it results in:

We could then defined a handy (SASS) mixin:

@mixin aspectRatioSizer($w:1, $h:1) {
&:before {
content:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 #{$w} #{$h}"></svg>');
}
display:grid;
&:before, >* {grid-area: 1 / 1 / 2 / 2;}
}

And smoke it with:

#myel {
@include aspectRatioSizer(7,2);
}