Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackycute/bcb44b6b5693d273d0d9 to your computer and use it in GitHub Desktop.
Save jackycute/bcb44b6b5693d273d0d9 to your computer and use it in GitHub Desktop.
3 ways to keep div ratio responsively (pure CSS)

3 ways to keep div ratio responsively (pure CSS)

To keep div in ratio might be a problem sometimes.
Here shows 3 ways to keep it.

  • apply to the element directly
  • apply to its pseudo element
  • use a placeholder image (might able to generate by js using canvas)

A Pen by WuChengHan on CodePen.

License.

<!-- from http://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css -->
<div class="direct">
<div class="wrapper">
<div class="content">
16:9
</div>
</div>
</div>
<br>
<!-- from https://css-tricks.com/snippets/sass/maintain-aspect-ratio-mixin/ -->
<div class="pseudo">
<div class="content">
16:9
</div>
</div>
<br>
<!-- from myself :) -->
<div class="image">
<img src="https://upload.wikimedia.org/wikipedia/commons/e/e1/B757_(7518728768).jpg">
<div class="content">
16:9
</div>
</div>
.direct, .pseudo, .image {
width: 10%;
background: gold;
animation: 5s linear rwd infinite alternate;
}
@keyframes rwd {
from {
width: 10%;
}
to {
width: 30%;
}
}
.direct {
position: relative;
}
.direct > .wrapper {
position: relative;
width: 100%;
padding-bottom: 56.25%;
}
.direct > .wrapper > .content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.pseudo {
position: relative;
}
.pseudo:before {
display: block;
content: "";
width: 100%;
padding-top: 56.25%;
}
.pseudo > .content {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.image {
position: relative;
}
.image > img {
position: absolute;
width: 100%;
object-fit: contain;
}
.image > .content {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment