Luiz Borges
Luiz Borges

Reputation: 567

Simulate tab in CSS

Is there anyway to simulate Tab positions with CSS.

Like:

..........|.........|..........|.........
Text!     Next tab  |          |
Longer text!        Next tab   |
Even more longer text!         Next tab

How can I simulate this behavior?

PS: If it not obvious, I don't know the text length in advance.

Upvotes: 5

Views: 5057

Answers (4)

e.c
e.c

Reputation: 61

If it doesn't have to be perfect (as the OP said Jun 12 '11 at 12:05), at least in ie7, a <pre> block already supports tabbing with tab-chars (fixed at 8 char-widths [ref] unless tab-size is supported [ref]), and, maybe useful here too, a style-attribute to override the default monospace font.

Upvotes: 1

Nick Schappler
Nick Schappler

Reputation: 33

Here is a way that I got around a similar problem, but the success of this method will depend on your specific application.

Rather than thinking about it as a string with tabs, try using an HTML Table with a border of 0. Each column is perfectly aligned so it's like a tab.

<table border="0">
 <tr>
   <td>not tabbed</td>
   <td>1 tab over</td>
   <td> </td>
 </tr>
 <tr>
   <td>not tabbed</td>
   <td> </td>
   <td>2 tabs over</td>
 </tr>
</table>

will give you what you want - or you can modify it to do so

Upvotes: 0

NGLN
NGLN

Reputation: 43664

A pure CSS solution seems unlikely to me for this behaviour. So if you turn into using javascript, it might look like this:

HTML:

<div id="tabs">
    <p><span>Text!</span><span>Next tab</span></p>
    <p><span>Longer text!</span><span>Next tab</span></p>
    <p><span>Even more longer text !</span><span>Next tab</span></p>
</div>

Javascript:

var tabs = document.getElementById('tabs');
var ps = tabs.getElementsByTagName('p');
var p;
var spans;
var span;
var w;
var wTab = 70;

for (var i = 0; i < ps.length; i++)
{   p = ps.item(i);
    spans = p.getElementsByTagName('span');
    for (var j = 0; j < spans.length - 1; j++)
    {   span = spans.item(j);
        w = span.offsetWidth;
        w = Math.ceil(w / wTab) * wTab - w;
        span.style.paddingRight = w + 'px';
    }
}

See also Demo fiddle.

Disclaimer: I'm a noob at javascript, and surely don't know anything about javascript frameworks, so it's highly probable this routine can be optimized.

Upvotes: 2

NGLN
NGLN

Reputation: 43664

You should use table for showing tabular data: see this demonstration fiddle.

Upvotes: 0

Related Questions