Question

Take a look at http://www.barelyfitz.com/screencast/html-training/css/positioning/ item 6. It says:

It is not a viable solution for most designs, because we usually do not know how much text will be in the elements, or the exact font sizes that will be used.

What workaround do I need to use in order to insert dynamic text into a div with absolute position?

Any approach is welcome

regards,

Was it helpful?

Solution

If your primary goal is to keep the div in it's place, without changing it's height or width based on the amount of text, I'd go with:

div {
    overflow: scroll;
}

The other option is to have the text size shrink to fit into the div, but that involves a certain amount of fuzzy math and you run the risk of the text being so tiny it's pointless.

If you want the div to change it's height based on the text, this also involves some fuzzy math, but basically, you would get the length of the text with:

var sometext = "Hey, I'm some text!";
var textlength = sometext.length();

And make the height change in relation to that length. You'd want to play with the numbers, but it would look something like:

var div_height = 10 * textlength;
$("div").css("height,"+ div_height +"em");

OTHER TIPS

See Visual Effect section from W3C site here

Maybe using "overflow: auto" for the dynamic-text-container div.So the height isn't a problem.

The problem isn't putting the dynamic text in the absolutely positioned div - the div will expand to fit whatever text is in there. There are no heights defined on the red and green divs in your example.

Absolutely positioned divs are taken out of the flow of the document so anything that appears after them in the html will act like they aren't even there.

Designs that use absolutely positioned divs need to have a height defined on the containing div so the absolutely positioned divs don't overlap other content. In your example <div id="div-1"> has a height of 250px defined. Change that to 100px and you will see <div id="div-after"> move under the red and green divs.

So if you have a absolutely positioned div in a sidebar with nothing after it you can add all the dynamic text you want. If you have one in your header, it is going to make your design very complicated to implement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top