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?
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.
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.
To just center the text inside an element, use text-align: center; This text is centered.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With