Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

centering

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?

like image 375
Christoph Wurm Avatar asked Jul 25 '11 15:07

Christoph Wurm


People also ask

How do I center text in a float?

To center the text using float we can use margin-left or margin-right and make it 50% , like below. You can learn more about the uses of Float here.

How do you center a floated element in CSS?

The CSS float property is used to set or return the horizontal alignment of elements. But this property allows an element to float only right or left side of the parent body with rest of the elements wrapped around it. There is no way to float center in CSS layout.

How do you keep text centered in CSS?

To just center the text inside an element, use text-align: center; This text is centered.

How do you center anything with CSS align a div text and more?

You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.


2 Answers

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.

like image 127
Eric Avatar answered Nov 09 '22 01:11

Eric


Here's a link to a working fiddle: http://jsfiddle.net/cD657/3/

(in your example, you opened a <span>, and closed it with </div>)

I made it a div and gave it margin: 0px auto; and a width. -seemed to do the trick

like image 33
Dave Avatar answered Nov 09 '22 01:11

Dave