Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML/CSS: how to put text both right and left aligned in a paragraph

Tags:

html

css

What would be the best code to have two bits of text in a single paragraph, one left aligned, the other right aligned, that also is:

  • the least code as possible
  • the easiest for clients to render (i.e. using least resources)

I add this last one to be sure <table><tr><td></td><td align=right></td></tr></table> would get ruled out. Not only is this a beast of code compared to a couple of properly styled <div>, <span> or <p>'s, it's also a beast if you know what a HTML render engine has to load and calculate to decide on the cell sizes before it even get's to painting text in them...

If you're not sure what I mean, here's an example: a page footer with left aligned the name of the user currently logged on, and on the same line right aligned the current date and time and/or website version.

like image 236
Stijn Sanders Avatar asked Oct 27 '10 11:10

Stijn Sanders


2 Answers

Least amount of markup possible (you only need one span):

<p>This text is left. <span>This text is right.</span></p>

How you want to achieve the left/right styles is up to you, but I would recommend an external style on an ID or a class.

The full HTML:

<p class="split-para">This text is left. <span>This text is right.</span></p>

And the CSS:

.split-para      { display:block;margin:10px;}
.split-para span { display:block;float:right;width:50%;margin-left:10px;}
like image 72
Stephen Avatar answered Oct 14 '22 04:10

Stephen


The only half-way proper way to do this is

<p>
  <span style="float: right">Text on the right</span>
  <span style="float: left">Text on the left</span>
</p> 

however, this will get you into trouble if the text overflows. If you can, use divs (block level elements) and give them a fixed width.

A table (or a number of divs with the according display: table / table-row / table-cell properties) would in fact be the safest solution for this - it will be impossible to break, even if you have lots of difficult content.

like image 42
Pekka Avatar answered Oct 14 '22 02:10

Pekka