Saqib Ali
Saqib Ali

Reputation: 12575

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.

Upvotes: 0

Views: 85

Answers (4)

Mr_Green
Mr_Green

Reputation: 41832

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>

Upvotes: 2

GvM
GvM

Reputation: 1733

.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>

Upvotes: 2

dashtinejad
dashtinejad

Reputation: 6253

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>

Upvotes: 3

Ron.Basco
Ron.Basco

Reputation: 2438

.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>

Upvotes: 3

Related Questions