CSS: How can I center text despite a floating element beside it?

Christoph Wurm picture Christoph Wurm · Jul 25, 2011 · Viewed 17.4k times · Source

Basically, I want to center text, ignoring any floating sibling elements.

At first, I thought this wouldn't be a problem, as I was under the impression that a floating element did not take from the width of any sibling elements.

Example (I want the red text to be at the center of the blue box, despite the green text)

How is this best achieved?

Answer

Eric picture Eric · Jul 25, 2011

You can't. If it were centered within the parent box, then the float would overlap the content at some point, which would be defeating the point of the float. There are two approaches you can use here. If you know the width of the float, you can apply an equal negative right margin. Otherwise, you can absolutely position the element like this.