Center text and float div to the right

11,775

Something like this...

<div style='position:relative;'>
  my centered text
  <div style='position:absolute;right:0;top:0'>
    my right div
  </div>
</div>

You can obviously throw the inline styles into CSS.

Share:
11,775
TheBoss
Author by

TheBoss

Updated on July 25, 2022

Comments

  • TheBoss
    TheBoss almost 2 years

    I have a container div which has text within it that I want centered. I want to also insert a div into the container which floats to the right, like this:

    <div id="container" style="text-align:center">
      Text
      <div id="child" style="float:right"></div>
    </div>
    

    Unfortunately what happens is that the text is no longer centered with respect to the container, but is instead shifted to the left by the width of the child.

    Does anyone know how to get the text to center whilst keeping the div contained to the right?

    • TheBoss
      TheBoss over 11 years
      No, although it will very rarely change width.
  • TheBoss
    TheBoss over 11 years
    That would indeed work, but is there a tidier solution (one that does not require 2 extra divs)?
  • anson
    anson over 11 years
    just keep in mind the "absolute" div will render above your "centered" text, if the centered text is too long.
  • Zak
    Zak over 11 years
    You could float the one right, and float #2 (with text) to the right, and forget #3, just set container to a width of 90px maintaining that the other two are still set to 30
  • TheBoss
    TheBoss over 11 years
    Excellent. I tried this but wasn't aware that there was a "right" attribute! I thought I'd have to resort to using JavaScript which would be a nuissance for something as simple as this. By the way, your answer can be improved by including top:0; as well so that it aligns it with the containing div. Thanks!