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
Susan SarandonOriginal
2024-12-06 07:16:11496browse

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/

HTML:

<div>

CSS:

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

JavaScript:

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

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!

Statement:
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