简体   繁体   中英

How to fit content of a DIV with fixed height

Consider that we have a DIV with fixed height. Without a defined width , the content will spread to the width of 100%. How to adjust the width to fill the DIV. Definitely, it is not posible with CSS, thus, I am looking for a solution with Javascript.

In this example , the text is spread across the width of 100% and leaves lots fo empty space in the fixed height. I need to set a width of 130px by javascript to fit the content to the entire DIV. But how to calculate the width?

NOTE: This value (130px) was estimated for the example text. Depending on the DIV content, javascript needs to calculate the width required to fit the content within the DIV.

Is there any way to estimate the 2D size of a DIV content?

CSS actually does this for height; when we have a fixed width, it continues the height to fill the DIV. Is it possible to do so for width too?

Clarification: How to vertically fill the DIV without knowing the width (we have a fixed height)?

If I understand your requirement correctly, you can do this using Javascript.

The trick is to use a helper <div> within which you let the browser flow the content to a specific width and see what height it comes up with. If the height of the helper <div> is more than that of the outer <div> , adjust the width to compensate.

Meanwhile, the outer <div> has overflow: hidden so all those flowing experiments don't produce jarring changes to your page layout.

See it in action .

This is an alternate approach.. While less efficient, it may be more accurate than my other answer.

see example here:

Basically loop the width down until the desired height is reached

<div id="AA">
    <div id='A'>
        I dont know how wide i am, I dont know how wide i am, I dont know how wide i am, I dont know how wide i am, I dont know how wide i need to be
    </div>
</div>

The CSS:

#AA {
    height: 300px;
    border: 1px solid black;
    width: 100%;
}

#A {
   display: inline;
}

The Script:

    height = $('#AA').height();
minWidth = 300;

currentWidth = $('#A').width();
currentHeight = $('#A').height();
stop = false;

if (currentWidth >= minWidth) {

    while (stop === false) {
        if (currentWidth >= minWidth) {
            newWidth = currentWidth - 1;
            $('#AA').width(newWidth);
            currentHeight = $('#A').height();
            currentWidth = $('#A').width();
            if (currentHeight < height) {
                stop = false;
            }
            else {
                stop = true;
            }
        }
        else {
            stop = true;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM