简体   繁体   中英

Align text within div tags

I've this below html

str+="<div class='label' date1='"+a+"' date2='"+a1+"' id='mydiv'> Start Date "+a;
str+="End Date "+a1;

Now I want date1 should be aligned left to the page and date2 should be aligned right to the page.

How to do this?

Regards

Try like this: Demo

CSS:

.fl{ float:left; }
.fr{ float:right; }
.label{ clear:both; }

HTML:

<div class="label" date1="10/5/2016" date2="10/20/2016" id="mydiv">
    <span class="fl">Start Date 10/5/2016</span> 
    <span class="fr">End Date 10/20/2016</span>
</div>

Make it simple with flexbox and pseudo elements .

 #mydiv { display: flex; justify-content: space-between; } #mydiv::before { content: "Start Date: " attr(date1); } #mydiv::after { content: "End Date: " attr(date2); } 
 <div class="label" date1="10/5/2016" date2="10/20/2016" id="mydiv"></div> 

So, your code will be like this:

str+="<div class='label' date1='"+a+"' date2='"+a1+"' id='mydiv'></div>";

This is gonna save your time

///HTML

<div class="label" date1="10/5/2016" date2="10/20/2016" id="mydiv"><div style = 'float:right'>End Date 10/20/2016
</div>
</div>Start Date 10/5/2016></div>

Live demo: https://jsfiddle.net/c6wnsob6/3/

wrap the dates in span and add css as below

<div class="label" date1="10/5/2016" date2="10/20/2016" id="mydiv">
    <span class="float-left">Start Date 10/5/2016</span>
    <span class="float-right">End Date 10/20/2016</span>
</div>

CSS

.float-left{float:left;}
.float-right{float:right;}

try this codepen codepen ..

I wrapped two dates in two spans and used display: inline-block; to the span elements to align inline with width and for the first element i used text-align: left; to start from left and for the second element used text-align: right; to start from right.

Note: I given max-width: 800px; to the parent element but you can give your width or you can remove.

You can put the both dates in span or p tag and make one element float to left and other to right.

UPDATED as per your code

 $str .="<div class='label' date1='".a."' date2='".a1."' id='mydiv'><span style='float:left'> Start Date ". a.'</span>';
$str.="<span style='float:right'>End Date ".a1.'</span>';

use float:left and float:right for dates.

 .label { width: 100%; height: auto; max-width: 800px; } .date-1 { width: 50%; text-align: left; float:left } .date-2 { width: 50%; text-align: right; float:right; } 
 <div class="label" date1="10/5/2016" date2="10/20/2016" id="mydiv"><span class="date-1">Start Date 10/5/2016</span><span class="date-2">End Date 10/20/2016</span></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM