lordvlad
lordvlad

Reputation: 5347

make overflowing text readable with css

i have a table with fixed-width content. which does not always fit. i would like to truncate the text to a fixed width and append an ellipsis. the full text should be visible when hovering the text. this works fine, except that the now visible text covers text to its right. how can i prevent this?

this is what i've got so far.

.truncate {
  max-width: 5em;
  overflow: hidden;
  display: inline-block;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.truncate:hover {
  overflow: visible
}

jsFiddle

Upvotes: 1

Views: 1322

Answers (2)

Viktor S.
Viktor S.

Reputation: 12815

Here is how your approach could be improved so text will be readable when hovered.

Updated HTML:

<table>
    <tr>
        <td><span><a class="truncate">faksjfaklsjf asjf lajslfk jasklfj alkjsfkl jalskfjla</a></span>
        </td>
        <td>
            <span>
            <a class="truncate">
                faskfjalskfj alkfj laksj flkajfl kajfl ajfkl ajsl
            </a>
            </span>
        </td>
    </tr>
</table>

See how <a> is now wrapped with <span>.

And here is updated CSS:

td {
    width: 5em;
} 
span {
    height:1.2em;
    position:relative;
    display: inline-block;
}
.truncate {
     max-width: 5em;
     overflow: hidden;
     display: inline-block;
     text-overflow: ellipsis;
     white-space: nowrap;

 }
 .truncate:hover {
    position:absolute;
    max-width: none;
    background:#fff;     
    z-index:100;
    overflow:visible;    
 }

span is relatively positioned, so absolute item inside it will be shown in a new layer and will take virtually no space (will not shift other text when overflow:hidden removed).

a.truncate will now became absolutely positioned on hover and will loose max width restriction. background:#fff is required to

Demo

Upvotes: 5

Jacques Snyman
Jacques Snyman

Reputation: 4290

Add a title attribute to your tag and remove the hover CSS:

HTML

<table>
    <tr>
        <td>
            <a class="truncate" title="faksjfaklsjf asjf lajslfk jasklfj alkjsfkl jalskfjla">
                faksjfaklsjf asjf lajslfk jasklfj alkjsfkl jalskfjla
            </a>
        </td>
        <td>
            <a class="truncate" title="faskfjalskfj alkfj laksj flkajfl kajfl ajfkl ajsl">
                faskfjalskfj alkfj laksj flkajfl kajfl ajfkl ajsl
            </a>
        </td>
    </tr>
</table>

CSS

td {
    width: 5em;
} 
.truncate {
     max-width: 5em;
     overflow: hidden;
     display: inline-block;
     text-overflow: ellipsis;
     white-space: nowrap;
 }

Fiddle here

Upvotes: 1

Related Questions