This issue appeared when programming a custom pop-up solution for a client. CSS and font-size property with variable width didn't work because there's no knowing in how much text will the client enter in production so setting this to a value could work now, but if they add or remove a lot of text then there's a problem.
Alternative was to write a bit of css and jquery code.
So, my html with the pop-up content looks like this:
Pop-up content goes here...
My CSS:
.p-content{background:#ad006d;color:#fff;width:100%;
position:relative;
left:0;
right:0;
margin-top:20px;
padding:20px 40px;
font-size:20px;
height:100%;
max-height:260px;
}
The CSS is used to define the height and max height of the element. Now we use jquery to modify the font size.
I wrote a function, named it "setup_fontsize" and called it on document ready and on window resize.
jQuery(document).ready(function(){
setup_fontsize();
});
jQuery( window ).resize(function() {
setup_fontsize();
});
function setup_fontsize(){
jQuery(".p-content").attr('data-fs', 20 );
jQuery(".p-content").css('font-size', "20px");
if(jQuery(".p-inner").height()>jQuery(".p-content").height()){
var i =0;
while(jQuery(".p-inner").height()>jQuery(".p-content").height() && i<10){
fontsize = jQuery(".p-content").attr('data-fs')*0.9;
console.log("Setting new font size: " + fontsize);
jQuery(".p-content").css('font-size', fontsize + "px");
jQuery(".p-content").attr('data-fs', fontsize );
i++;
}
}
}
The idea is set the default font size (20px) on the content div. I also used the custom attribute "data-fs" for additional control.
If the height of the inner content div is greater than the height of the content div, which is limited by max-height css property, then start a while loop. While loop checks the height of the "p-inner" class div element, while the height is greater than the parent "p-content" class div element reduce the current font size by 10%. New font size is current font size fetched from the custom "data-fs" attribute, multiplied by 0.9 to get 90% of the value and then applying it on the content as css.
Now the loop goes again to check if the new font size works and the height of the inner content div is less than the main content div. If not, then reduce the font size by another 10%. This loops for 10 iterations to prevent infinite loops. After 10 iterations font size would be 6.97px. That's probably small enough.
So that's it! I hope this solution helps you.
If you need custom WordPress plugins, themes, or advanced carousel solutions, I can help. Let's bring your project to life!
Ključne riječi: dynamic font resize, font size to fit container, change font dynamically, font adjust, font resize