Skip to content Skip to sidebar Skip to footer

Css: Force Text To Wrap (or Defining Element Width By Only One Of Its Children)

Okay, this is a weird one to me. Here's the HTML element I'm working with: LOLZ http://www.ubuntu-pics.de/bild/14571/screenshot_030_0O2o3D.png A photo with a caption. Ideally, I'd

Solution 1:

Check out this great article on the best ways of handling the image-with-a-caption scenario.

Personally this is one of those cases where you gotta suck it up and go with that works.

Solution 2:

Make the container a table with table-layout:fixed and put the image in the top row. You can also do this with pure CSS using the display:table-* properties (and the IE7-js library for IE6 compatibility).

What table-layout:fixed does is make the table drawing algorithm lock the width of each table column once the width of the first cell in that column is known. The caption will have nowhere to expand to so it will wrap to the width of the image (the first cell).

Solution 3:

Alright, it looks like there's no simple solution that I can pull off. Thanks for helping me work that out :)

I think that, given how I'll be storing those images, accessing width won't involve constant recalculation. I may just use that server-side magic instead.

Thanks!

Solution 4:

Here's a solution that probably does not work for you even though it does produce the layout you requested:

<!DOCTYPE htmlPUBLIC"-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"><html><head><style>div.a {float: left;
        position:relative;}

div.b {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        text-align: center;
        background-color:gray;}

</style></head><body><divclass="a"><imgsrc="http://stackoverflow.com/content/img/so/logo.png"alt=""><divclass="b">Caption text Caption text Caption text Caption text Caption text </div></div></body></html>

You see the reason why it is unsatisfactory if you place some content below the div a. It will overlap with the caption, because the absolutely positioned caption did not extend the parent div vertically. It still may work for you if you have enough white space below anyway or you are willing to reserve it.

Solution 5:

I came up with a working and fairly clean solution.

The solution uses a table (or div with display:table if you prefer) and adds a second column to "push" the first cell into the minimum space it really needs. The table can be set to 1px width to stop it growing across the page. I've put together a demo to show this in action:

http://test.dev.arc.net.au/caption-layout.html

Tested and working in IE8, Firefox and Safari/Win

Post a Comment for "Css: Force Text To Wrap (or Defining Element Width By Only One Of Its Children)"