Status
someone checked in 4.2GB of data files in my subversion repo. makes a global checkout "unfun"
Location
Alexandria, VA
Subscribe to GeoRSS Subscribe to KML


Floating text below an absolutely positioned div

Published in Howto, Programming, Web  |  4 Comments


This is probably odd to most people, but for a project I had to put a caption below an image on a webpage. But I wanted the image to be fixed in position and the caption would automatically flow and remain centered no matter how long the string was. I knew the size of the image (original div) but not the text string.

CSS CaptionThe trick lies in embedding the caption div within another div. Then the outer div should have a left: equal to half the image (or other div)’s width. The relevant CSS is:


outercaption {
	position: relative;
	left: 13px;
	}
.caption {
	text-align: center;
	position: relative;
	left: -50%;
	white-space: nowrap;
	}

Which will work with this HTML code.


Short

Here is an example. You can even put in your own text to see how it is dynamically sized.

Similar Posts


Responses

  1. ramin says:

    January 23rd, 2006 at 3:14 am (#)

    Why don’t you use the HTML code:

    With the following CSS:

    .image {
    padding: 0 3em;
    margin: 0 auto;
    text-align: center;
    }

    .image img {
    margin: 0 auto;
    }

    .image p {
    clear: both;
    font-style: italic;
    text-align: left;
    }

    This works in IE, Mozilla/Firefox, and Opera and validates. The caption will remain centered with respect to the image. The only problem that you may have would be that the width of the caption can be greater than the image’s width, but that is easily solved.

  2. ramin says:

    January 23rd, 2006 at 3:16 am (#)

    Ugh… The previous comment’s HTML got mangled, so here’s another try:

    <div class=”image”>
    <img src=”…” alt=”…” />
    <p>…</p>
    </div>

  3. Andrew says:

    January 23rd, 2006 at 7:51 am (#)

    The problem with that solution is that the image will “float” within it’s parent div to remain centered above the text. I need the image to remain fixed to the page, and have the text float beneath it. Using margin: 0 auto; is definitely the solution if you don’t mind the image moving.

    Ramin Example Here.

  4. qgoauxqkvc says:

    June 20th, 2007 at 8:52 pm (#)

    Hello! Good Site! Thanks you! glnpfpeqcpjf

Leave a Response