As noted many times by many people, it is not possible to set a width based on 100% height using pure CSS.
If you know or can figure out the aspect ratio, then you technically know the width, and you can calculate it fairly easily.
.wrapper {
position: relative;
width: 100%;
padding-top: 56.25%; /* 16:9 or widescreen aspect ratio */
}
.hexagon {
top: 0;
position: absolute;
width: calc(100% * 9 / 16); /* or simply 56.25%; */
}
If the aspect ratio is unknown, then the only viable solutions using CSS is to set the height (or min-height) of the parent element using px
or em
values. These can also be set using CSS variables, although CSS variables are not fully supported by some older browsers.
.wrapper {
min-height: 400px;
}
.hexagon {
width: calc(400px * 0.57735);
}
Finally, if the height is completely dynamic, for instance it changes based on the number of lines of text, then the width will need to be calculated using javascript.
// Example using jQuery, but the principles should be the same.
jQuery(function($){
var hexagon = $('.hexagon');
// Resizing the document may change the height of the parent element.
$(window).on('resize', function() {
hexagon.each(function(){
// We'll remove the existing width before calling parent.height()
$(this).css({width:''}).css({width:$(this).parent().height()});
});
}).trigger('resize');
});
Please note that the javascript solution may not provide the exact results you are looking for if the size of the parent element changes when the child element changes. This is also part of the challenge with using height values with CSS and why almost everything is based on width instead.
calc()
doesn't use the width of anything, it just do the simple operation between the left-hand side and the right-hand side by the operator. . So in the case of relative values (like here100%
) it first converts this value to an absolute one. You can't pass another element's relative value nor an other preoperties btw...