简体   繁体   中英

CSS: How can I right-justify text against centered text?

Given the following HTML:

<div class="css_class_1">
    <div class="css_class_2">
        A 1 A 1 A 1
    </div>
    <div class="css_class_3">
        B 2 B 2
    </div>
</div>

I would like to make the text A 1 A 1 A 1 horizontally-centered. And I would like to make the text B 2 B 2 right-justified so that it's right border is aligned with the right border of A 1 A 1 A 1 .

How can I do it? Please show the css I should define for each of the three mentioned classes.

 .css_class_2{ text-align: right; } .css_class_3{ text-align: right; } .css_class_1{ position: absolute; top: 0; left: 50%; transform: translateX(-50%) } 
 <body> <div class="css_class_1"> <div class="css_class_2"> A 1 A 1 A 1 </div> <div class="css_class_3"> B 2 B 2 </div> </body> 

Put your right justify text inside the center one:

 .css_class_1 { background: green; padding: 10px; } .css_class_2 { background: yellow; text-align: center; display: inline-block; } .css_class_3 { background: red; text-align: right; } 
 <div class="css_class_1"> <div class="css_class_2"> A 1 A 1 A 1 <div class="css_class_3"> B 2 B 2 </div> </div> </div> 

 .css_class_2 { text-align: center; border-right: 2px solid dodgerblue; background-color: peachpuff; margin-bottom: 10px; } .css_class_3 { text-align: right; border-right: 2px solid dodgerblue; background-color: peachpuff; margin-bottom: 10px; } .css_class_1 { text-align:center; } .parent { display:inline-block; } 
 <div class="css_class_1"> <div class="parent"> <div class="css_class_2"> A 1 A 1 A 1 </div> <div class="css_class_3"> B 2 B 2 </div> </div> </div> 

You just need to give the following css

 .css_class_1 { display: inline-block; text-align: right; } body { /* or grand parent element */ text-align: center; } 
 <div class="css_class_1"> <div class="css_class_2"> A 1 A 1 A 1 </div> <div class="css_class_3"> B 2 B 2 </div> </div> 

Or

If you are fine with CSS3's width: max-content , you can make it smaller.

 .css_class_1 { text-align: right; width: max-content; margin: 0 auto; } 
 <div class="css_class_1"> <div class="css_class_2"> A 1 A 1 A 1 </div> <div class="css_class_3"> B 2 B 2 </div> </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