In my fluid layout, I have a div with a required aspect ratio of 1:1. This div can contain text, an image, or both.
The challenge is to vertically align the text and ensure the image fits within the div without exceeding its boundaries or losing its aspect ratio.
Although I have successfully achieved most of this, I'm struggling with keeping the image aligned and proportionate to the div size simultaneously.
Here's how I maintain the 1:1 ratio of the div:
#upload-drop{
background-color: #e6e6e6;
position: relative;
}
#upload-drop:before{
content: "";
display: block;
padding-top: 100%;
}
#upload-drop >div{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
To vertically align content, I use the following CSS:
.valign-center{
text-align: center;
white-space: nowrap;
}
.valign-center:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em;
}
.valign-center-content{
display: inline-block;
vertical-align: middle;
}
For images, I apply the following styles to maintain their aspect ratio and fit inside the parent div:
#upload-img {
width: 100%;
height: 100%;
}
img{
width:auto;
height:auto;
max-width: 100%;
max-height: 100%;
}
If I remove width and height on #upload-img
, everything aligns perfectly, but portrait images may no longer fit the div properly.
How can I ensure both alignment and proper fitting for all types of content?