Floating text below an absolutely positioned div

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.

About this article

written on
posted in ProgrammingWebHowto Back to Top

About the Author

Andrew Turner is an advocate of open standards and open data. He is actively involved in many organizations developing and supporting open standards, including OpenStreetMap, Open Geospatial Consortium, Open Web Foundation, OSGeo, and the World Wide Web Consortium. He co-founded CrisisCommons, a community of volunteers that, in coordination with government agencies and disaster response groups, build technology tools to help people in need during and after a crisis such as an earthquake, tsunami, tornado, hurricane, flood, or wildfire.