22

I am not sure how to get the following behaviour using a combination of HTML and CSS:

foo    = this
foobar = bit
goso   = needs
etcetc = aligning

Now I could just insert spaces where required (like I did above), but I'm pretty sure there must be a way to do this "automatically".

I know I could use tables to do this, but would prefer not to. Is there any other way of doing this?

My question boils down to this: How do I automatically align text vertically, in a similar way to tabs in office suites, using HTML/CSS.

Here is an in context example:

<p><span class="a">foo</span> <span class="b">=</span> <span class="c">"abcDeveloper"</span></p>
<p><span class="a">bar</span> <span class="b">=</span> <span class="c">"123"</span></p>
<p><span class="a">foobar</span> <span class="b">=</span> <span class="c">"dfg"</span></p>
<p><span class="a">foobarstar</span> <span class="b">=</span> <span class="c">"456"</span></p>

In this example, I would like text in class b to be aligned vertically.

Thank you in advance!

2
  • This is what tables are for.
    – stark
    Commented Nov 17, 2013 at 22:56
  • @stark surely there must be another way though? If I'm writing something simple like an office document I do not have to create a table to align everything. I was hoping HTML/CSS had a similar solution to tabs.
    – OMGtechy
    Commented Nov 17, 2013 at 22:57

2 Answers 2

29

One method would be to apply display: inline-block; to your span.as, and then give them a set width: http://jsfiddle.net/nzrHn/1/

.a { display: inline-block; width: 100px; }
4
  • Yes, this is a good approach. But width : *** could probably help, too.
    – Nico
    Commented Nov 17, 2013 at 23:00
  • @Nico I tried that, but it does nothing. Could you explain please?
    – OMGtechy
    Commented Nov 17, 2013 at 23:01
  • What I meant is, if you know all fields are at most 180px (for instance), then you fix the width of span.a to 180px and the width of span.b to 15px (or whatever suits you best). That way all = signs will be aligned, providing you with a rather ugly way of simulating a table. Still recommend a table, makes this just automatic!
    – Nico
    Commented Nov 18, 2013 at 8:51
  • Use em rather than px if you want a relative rather than an absolute unit. The former is relative to the font size and scales as the font size scales.
    – nmit026
    Commented Jan 30, 2019 at 6:55
4

Add css attribute display: inline-block and min-width: XXXpx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.