I use the following style to vertically and horizontally align content.
.middle_center{
top: 50%;
left: 50%;
transform:translate(-50%,-50%);
}
However, if the content of .middle_center is larger than 50%, the left:50% applied means the width of .middle_center can only stretch to 50% of it's parent.
Here is a full code:
.parent{
position:relative;
background:#ff00ff;
width:800px;
height:300px;
}
.middle_center{
position:absolute;
background:#0000ff;
color:#fff;
padding:20px;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
<div class="parent">
<div class="middle_center">This is some content. The left:50%; causes its width to be reduced to 50% of its parent's width.</div>
</div>
If I apply width: fit-content;
then it works as expected. However this isn't supported by all browsers.
Does anyone know of a way to prevent the width from shrinking? It would like to add CSS only to the child element without adding styles to the parent if possible.
Here is a codepen link: