Reputation: 106920
I want to position text inside an element (fixed width) in such a way, that if it is short enough, it will be centered, but if it's too long to fit, it will be left-aligned, and the end of the text will be cut off (via overflow: none
). In this case there will be a tooltip (via title=""
) with the full text. How can I do it?
The element I'm referring to is a title beneath a picture. Since there are many pictures side-by-side, I don't want the titles to overlap or anything (they are absolutely positioned beneath the picture with fixed width and height). For a title it will look better if it's centered, but a lengthy string with overflow:none
that gets both ends cut off because of centering will look bad. Currently I have this:
<div class="ImageTitle">
<table style="margin: auto">
<tr><td title="The title">The title</td></tr>
</table>
</div>
This is hackish to say the least, but I can't seem to get it working with simple DIV
s and SPAN
s. Any ideas?
Upvotes: 1
Views: 2516
Reputation: 7727
Does this help? (I'm sorry, it's late here, I'm tired and unconcentrated)
<!doctype html>
<html>
<head>
<style type="text/css">
.outer {
max-width: 100%;
overflow: hidden;
}
.inner {
display:inline-block;
max-width:inherit;
white-space: nowrap;
text-align:left;
}
</style>
</head>
<body>
<div style="width:8em;text-align: center; border: 1px solid black">
<div class="outer">
<span class="inner">
Short cap
</span>
</div>
<p />
<div class="outer">
<span class="inner">
A very long caption
</span>
</div>
</div>
There's got to be a proper way to fix height, though.
Upvotes: 1
Reputation: 253318
I think that this should do what you want:
div.ImageTitle {
width: 100px; /* or whatever */
white-space: nowrap;
text-align: center;
overflow: hidden;
}
Note that I'm assuming the removal of the (unnecessary table
), if the table's still there then its css will override that of the div.imageTitle
.
While this doesn't conditionally assign either text-align: center
or text-align: left
, the former (text-align: center;
) will simply move from the centre of the element to the left margin of the element naturally (unless text-direction
is set to something other than ltr
), and over-flow on the right. To ensure that it remains on only one line, I've used white-space: nowrap
to remove wrapping.
For the tooltip I'm afraid that will have to be hardcoded into the div
(or whatever other element you use), since there's no way to use html so that it can work with if/else statemnts. If you're willing to use JavaScript then it's possible, but not with just html/css.
Upvotes: 2