1

I have a div that has text that is right aligned. I want to then center that div within its parent.

The code below only applies the right-alignment.

CSS

.outerDiv {
    text-align: center;
    width: 100%;
}

.innerDiv {
    text-align: right;
    width: auto;
}

HTML

<div class="outerDiv">
    <div class="innerDiv">
        10<br/>
        <span style="border-bottom: 1px solid black">
            + 2
        </span><br />
        12
    </div>
</div>

I know this can be done with using margin-left: auto; margin-right: auto in the outer div, but that requires that you set the inner div's width, which I don't know ahead of time.

Ideas?

dx_over_dt
  • 13,240
  • 17
  • 54
  • 102

2 Answers2

2

Since you're setting text-align: center on the parent element, you could simply set the display of the inner element to inline-block. In doing so, the inner element will be centered horizontally due to the fact that it has a "shrink-to-fit" width based on the width of its contents:

.outerDiv {
  text-align: center;
}
.innerDiv {
  display: inline-block;
  text-align: right;
}
.innerDiv span {
  display: block;
  border-bottom: 1px solid black
}
<div class="outerDiv">
  <div class="innerDiv">
    10<span>+ 2</span>12
  </div>
</div>

I also removed the <br /> elements, and changed the display of the span element to block. You could also just replace it with a p element (since it's already block-level by default).

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
-1

You could use the <center> html tag:

<center>
    <div class="outerDiv">
        <div class="innerDiv">
            10<br/>
            <span style="border-bottom: 1px solid black">
                + 2
            </span><br />
            12
        </div>
   </div>
</center>