forked from Chalarangelo/30-seconds-of-css
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add constant-width-to-height-ratio snippet
- Loading branch information
Showing
2 changed files
with
80 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
### Constant width to height ratio | ||
|
||
Given an element of variable width, it will ensure its height remains proportionate in a responsive fashion | ||
(i.e., its width to height ratio remains constant). | ||
|
||
#### HTML | ||
|
||
```html | ||
<div class="constant-width-to-height-ratio"></div> | ||
``` | ||
|
||
#### CSS | ||
|
||
```css | ||
.constant-width-to-height-ratio { | ||
background: #333; | ||
width: 50%; | ||
padding-top: 50%; | ||
} | ||
``` | ||
|
||
#### Demo | ||
|
||
Resize your browser window to see the proportion of the element remain the same. | ||
|
||
<div class="snippet-demo"> | ||
<div class="snippet-demo__constant-width-to-height-ratio"></div> | ||
</div> | ||
|
||
<style> | ||
.snippet-demo__constant-width-to-height-ratio { | ||
background: #333; | ||
width: 50%; | ||
padding-top: 50%; | ||
} | ||
</style> | ||
|
||
#### Explanation | ||
|
||
`padding-top` and `padding-bottom` can be used as an alternative to `height` such that the percentage value | ||
causes an element's height to become a percentage of its width, i.e. `50%` means the height will be 50% of the element's width. This allows its proportion to remain constant. | ||
|
||
#### Browser support | ||
|
||
<span class="snippet__support-note">⚠️ `padding-top` pushes any content within the element to the bottom.</span> |