I need to left, center, & right align text on the same line. I have the following text:
I wrote the following code which works for left and right aligning text but does not work correctly for the center text.
HTML
<div id="textbox"> <p class="alignleft">1/10</p> <p class="aligncenter">02:27</p> <p class="alignright">100%</p> </div> <div style="clear: both;"></div>
CSS
.alignleft { float: left; } .aligncenter { float: left; } .alignright { float: right; }
For example, say you want the headings centered on a page, but the paragraphs to be left aligned. Then you'd use the type selector h2 and set the text-align property to center. You don't have to add any more code to align the paragraphs — by default, they'll be left aligned.
To just center the text inside an element, use text-align: center; This text is centered.
The attribute is used with the HTML <p> tag, with the CSS property text-align for the center, left and right alignment.
Using Text-align property Another way to align image to the left, centre or right of the page is to use the text-align property. The html code uses the <div> tag and inline CSS style.
Try this
UPDATED
HTML
<div id="textbox"> <p class="alignleft">1/10</p> <p class="aligncenter">02:27</p> <p class="alignright">100%</p> </div> <div style="clear: both;"></div>
CSS
.alignleft { float: left; width:33.33333%; text-align:left; } .aligncenter { float: left; width:33.33333%; text-align:center; } .alignright { float: left; width:33.33333%; text-align:right; }
Demo the code here: http://jsfiddle.net/wSd32/1/ Hope this helps!
=======UPDATE 2021:
You can now get the same results using HTML5 Flex to do this. No need for floating or clearing divs. Simply add Display: flex;
to the parent container holding the items you wish to position.
HTML
<div id="textbox"> <p class="alignleft">1/10</p> <p class="aligncenter">02:27</p> <p class="alignright">100%</p> </div>
CSS
#textbox {display:flex; flex-flow:row wrap;} .alignleft { width:33.33333%; text-align:left; } .aligncenter { width:33.33333%; text-align:center; } .alignright { width:33.33333%; text-align:right; }
Demo The Result Using Flex: http://jsfiddle.net/jcbiggar1/tsopnf4d/4/
More on Flex: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
The magic HTML5 way that works responsively is to use flex:
<div id="textbox"> <p class="alignleft">1/10</p> <p class="aligncenter">02:27</p> <p class="alignright">100%</p> </div> <div style="clear: both;"></div>
CSS
#textbox { display: flex; justify-content: space-between; }
Demo:
http://jsfiddle.net/sep4kf6a/1/
You'll find it avoids the awkward box wrapping that occurs with floats on a small screen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With