Search code examples
htmlcsscentertext-alignmenttext-align

Do I need to use another property other than "text-align" to center my DIV within a DIV?


I want to center a DIV within a parent DIV. I have tried using the recommende dsolution on SO -- How to horizontally center a <div> in another <div>?, but its not centering it. The basic layout is this

#revealScoreMobile {
  padding: 10px;
  display: block;
  text-align: center;
  width: 100%;
}

.stats {
  text-align: center;
  width: 100%;
  background-color: red;
  margin: 0 auto;
}
<div id="revealScoreMobile">
  ...
  <div class="stats" style="">
    <div class="score">5.0</div>
    (<span class="votesCast">1</span> votes cast)
  </div>
</div>

and yet as you can see from the Fiddle -- https://jsfiddle.net/5Lgu0uw3/2/, the child DIV is not centering within the parent, despite the fact I have

text-align:center;

in there. What gives? What else do I need to do to center that DIV within its parent?


Solution

  • I am not completely sure what you want, but if you want the inner DIV NOT have the full width, but only as much as its text contents require, make it an inline-block and erase the widthsetting (or give it a widthsetting less than 100%). inline-blocks are affected by text-align: center

    (note that I erased some superfluous settings, but put the ... content into its own DIV, since it otherwise would be on one line with the subsequent inline-block.

    #revealScoreMobile {
      padding: 10px;
      text-align: center;
    }
    
    .stats {
      display: inline-block;
      text-align: center;
      background-color: red;
    }
    <div id="revealScoreMobile">
     <div> ... </div>
      <div class="stats" style="">
        <div class="score">5.0</div>
        (<span class="votesCast">1</span> votes cast)
      </div>
    </div>