At times, I like to create a square (or any rectangle) that maintains its ratio regardless of size, using a technique similar to this method.
My Objective:
- To prevent the square from extending beyond the viewport on devices with limited height, such as a mobile phone in landscape mode.
Proposed Solution:
- Limit the width of the square to a certain percentage of the viewport height using
max-width: 90vh
- Expect the ratio to be maintained
CSS Code:
.square {
position: relative;
height: 0;
padding-bottom: 100%;
overflow: hidden;
}
.square-inner {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.mw { max-width: 90vh;} /* proposed solution */
HTML Code:
<div class="square mw">
<div class="square-inner"></div>
</div>
Expected Outcome:
- In viewports with limited height, the square should be limited to a maximum width of 90% of the viewport height
Actual Outcome:
- When viewport height is less than the width of the square:
- Width is restricted based on the
vh
value - Height is calculated from the unbounded width of the square
- Resulting in a vertically elongated rectangle
- Width is restricted based on the
The CSS specification states that the relative value is calculated based on the containing block, which should be the current width of the container.
Browser Behavior:
- Chrome 29.0.1547.65: behaves as expected
- Firefox 23.01: behaves as expected
Opera: does not respect vh at allNot validated with Opera 16+
Am I misinterpreting the specification, or could this be a potential bug in how browsers implement it?