Home > Web Front-end > CSS Tutorial > How Can I Automatically Adjust Text Size to Fit Within a Div?

How Can I Automatically Adjust Text Size to Fit Within a Div?

Susan Sarandon
Release: 2024-12-06 07:16:11
Original
499 people have browsed it

How Can I Automatically Adjust Text Size to Fit Within a Div?

Adapting Text Size to Fit a Div

In your situation, you have a background image with a div where you want to display text. However, you'd like the text's font size to automatically adjust to fit within the div. To accomplish this, consider the following solution:

jQuery Implementation:

http://jsfiddle.net/MYSVL/2/
Copy after login

HTML:

<div>
Copy after login

CSS:

#fitin {
    width: 300px;
    height: 100px;
    border: 1px solid black;
    overflow: hidden;
    font-size: 1em;
}
Copy after login

JavaScript:

$(function() {
    while( $('#fitin div').height() > $('#fitin').height() ) {
        $('#fitin div').css('font-size', (parseInt($('#fitin div').css('font-size')) - 1) + "px" );
    }
});
Copy after login

This code iteratively reduces the font size until the text fits snugly within the div.

The above is the detailed content of How Can I Automatically Adjust Text Size to Fit Within a Div?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template