CSS:尽管旁边有浮动元素,如何使文本居中?
基本上,我想将文本居中,忽略任何浮动的同级元素。
起初,我认为这不会成为问题,因为我的印象是浮动元素不会占用任何同级元素的宽度。
示例(我希望红色文本位于蓝色框的中心,尽管有绿色文本)
如何最好地实现这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能。如果它在父框内居中,那么浮动将在某个点与内容重叠,这将破坏浮动的点。您可以在此处使用两种方法。如果您知道浮动的宽度,则可以应用相等的负右边距。否则,您绝对可以这样定位元素。
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.
这是一个工作小提琴的链接:http://jsfiddle.net/cD657/3/
(在在您的示例中,您打开了一个
,并用
关闭了它)
我将其设为一个 div 并给了它
margin: 0px auto;
和宽度。 -似乎成功了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您可以保持现有状态,但只需在另一侧添加填充,其像素值与浮动元素的宽度相同。
要轻松找到宽度,只需在任何现代浏览器中使用
开发人员工具
来检查
元素即可。请参阅此处的小提琴: http://jsfiddle.net/cD657/369/
注意: 如果居中元素具有指定的背景颜色,则这可能不起作用。
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.
To find the width easily just use
Developer Tools
in any modern browser toInspect
the element.See fiddle here: http://jsfiddle.net/cD657/369/
Note: This may not work if the centered element has an assigned
background
color.