I am using CSS and I want to create a box with a certain ratio that is kept no matter the size of the box. But also I want the box to grow if there is more content in it.
To summerize in order words:
- CSS only (if possible)
- preserve given aspect ratio
- allow box to grow if there is more content (with ratio)
In those techniques I've tried so far the content of the box is not able to make the box grow. Instead my only options are overlapping or clipping the content.
The first and the third method are preoccupying the space inside of a wrapper and the content is place on top of that using absolute position. Since the content is absolutely positioned it is removed from the document flow. Therefore it is unable to expand the wrapping element.
The Second Option is using a fixed height, which doesn't allow the content to grow beyond it either.
Here is a demo using the second option. (based on viewport units)
* {margin: 0; padding: 0;}
div{
width: 50vmin; height: 50vmin;
font-size: 30px;
background: #ccc;
margin: auto;
padding: 3%;
}
<div>
<p>If you scale your window, you will see that the text does not fit into the box at some point, and therefore the text will be overlapping the box.<p>
</div>
Further Methods I partially tested:
- object-fit positioning
- flexbox
Object-Fit only affects replaced-elements as far as I know. I am unable to get any effect on my div/p-elements with this properties.
Flexbox is not practical either for my scenario. According to my current level of knowledge flexbox does not help here very well. Since its mostly about establishing relationships between multiple items. But I am not sure about that. Maybe there is something in flexbox that I am not aware of yet.
div { font-size: 4.5vmin; }
– Bridoonobject-fit
property: https://mcmap.net/q/1168767/-fill-a-div-with-an-image-respecting-aspect-ratio – Carmine