Re-using floatLeft and floatRight to right align text

181 views Asked by At

How can i right-align text as below. I want product, price and year to be right-aligned.

   product       Computer
     price       $1500
      year       2013

Currently the html code below gives layout as shown

product     Computer
price       $1500
year        2013   

<div style="clear: both;display: block;">
     <p style="float: left">
         <strong>product</strong>
     </p>
     <p style="float: left">
         <span>Computer</span>
     </p>    
</div>

<div style="clear: both;display: block;">
     <p style="float: left">
         <strong>price</strong>
     </p>
     <p style="float: left">
         <span>$1500</span>
     </p>    
</div>

<div style="clear: both;display: block;">
     <p style="float: left">
         <strong>year</strong>
     </p>
     <p style="float: left">
         <span>2013</span>
     </p>    
</div>
4

There are 4 answers

0
kangoroo On

try display: inline-block, does wonders

0
cbr On

Try aligning the left-floated words with text-align:right;.

8
insertusernamehere On

I would solve it using inline-block elements instead of floating ones. To stick a little to your markup you could do:

HTML

<div class="row">
     <span>product</span>
     <span>computer</span>
</div>

<div class="row">
     <span>price</span>
     <span>$1500</span>
</div>

CSS

div.row > span {
    display: inline-block;
    width: 100px;
    text-align: right;
    margin: 0 20px 0 0;
}

div.row > span:last-child {
    width: 200px;
    text-align: left;
}

Demo

Try before buy

As a note: You might think of using another element for your content:

A paragraph is typically a run of phrasing content that forms a block of text with one or more sentences that discuss a particular topic, as in typography, but can also be used for more general thematic grouping. For instance, an address is also a paragraph, as is a part of a form, a byline, or a stanza in a poem.

If your data is actually tabular, you can use a <table>-element instead. You can also go with some markup like I did, or you can even use a definition list <dl> or an unsorted list <ul>.

Edit

As requested in the comments. Here's a version using a table:

HTML

<table>
    <tbody>
        <tr>
            <td>Product</td>
            <td>Computer</td>
        </tr>
        <tr>
            <td>Price</td>
            <td>1500 USD</td>
        </tr>
    </tbody>
</table>

CSS

table {
    width: 350px;
}

table > tbody > tr > td:first-child {
    width: 100px;
    padding: 0 50px 0 0;
    text-align: right;
}

Demo

Try before buy

2
abpetkov On

Give the <p> tags some width and margin to your last child element inside the <div>. Then assign text-align: right to your first child element. It should look something like this jsFiddle example.