ratio-box
view sourceGive an element with unknown or fluid width a fixed aspect ratio.
- use-name
-
scut-ratio-box
- type
- mixin, with default-values placeholder
- arguments
-
-
$ratio
- default
-
1/1
-
This is especially useful if you want a background-image
to preserve a ratio as a regular <img>
can. (For more details on how you might tailor the presentation of those background-image
s, have a look at the Nicholas Gallagher reference below.)
An important note: Any content you put inside the ratio-boxes needs to be absolutely positioned. Otherwise it will screw with the ratio. So position: relative
is set on the ratio-box to ease that. See the last example.
example
HTML
<p>These containers have different widths, but the ratio-boxes remain squares.</p><div class="eg-ratio eg-ratio-1"></div>
<div class="eg-ratio eg-ratio-2"></div>
<p>And the same principle applies to these, which maintain a 16/9 ratio and use a different classname for the inner element:</p>
<div class="eg-ratio eg-ratio-3"></div>
<div class="eg-ratio eg-ratio-4">
<div class="eg-ratio-inner">Content inside</div>
</div>
SCSS
.eg-ratio {
background: $eg-muted;
}
.eg-ratio-1 {
width: 15em;
@include scut-ratio-box;
// or @extend %scut-ratio-box;
}
.eg-ratio-2 {
width: 7em;
@include scut-ratio-box;
}
.eg-ratio-3 {
width: 15em;
@include scut-ratio-box(16/9);
}
.eg-ratio-4 {
width: 7em;
@include scut-ratio-box(16/9);
}
.eg-ratio-inner {
position: absolute;
top: 0;
left: 0;
}
compiled CSS
.eg-ratio {
background: #CCCCCC;
}
.eg-ratio-1 {
width: 15em;
overflow: hidden;
position: relative;
}
.eg-ratio-1:before {
content: "";
display: block;
height: 0;
padding-top: 100%;
}
.eg-ratio-2 {
width: 7em;
overflow: hidden;
position: relative;
}
.eg-ratio-2:before {
content: "";
display: block;
height: 0;
padding-top: 100%;
}
.eg-ratio-3 {
width: 15em;
overflow: hidden;
position: relative;
}
.eg-ratio-3:before {
content: "";
display: block;
height: 0;
padding-top: 56.25%;
}
.eg-ratio-4 {
width: 7em;
overflow: hidden;
position: relative;
}
.eg-ratio-4:before {
content: "";
display: block;
height: 0;
padding-top: 56.25%;
}
.eg-ratio-inner {
position: absolute;
top: 0;
left: 0;
}
Result
These containers have different widths, but the ratio-boxes remain squares.
And the same principle applies to these, which maintain a 16/9 ratio and use a different classname for the inner element:
Content inside
The ratio-box's ratio: a fraction signifying width / height. The default, 1/1, is a square. Photos and videos usually come in 4/3 or 16/9 ratios.