开发者

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

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

At firs开发者_JS百科t, 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?


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


You can keep as you have it but just adding padding on the opposite side with the same pixel value as the width of the floating element.

.parent{        
    text-align: center;
}
.centered.element{
     padding-left: [width of floating element]px;
}

.floating.element{
     float: left;
}

To find the width easily just use Developer Tools in any modern browser to Inspect the element.

See fiddle here: http://jsfiddle.net/cD657/369/

Note: This may not work if the centered element has an assigned background color.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜