CSS 使内容居中的适当方式 [英] CSS Appropriate Way to Center Content

查看:22
本文介绍了CSS 使内容居中的适当方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我更喜欢使用基于 CSS 的设计,但作为后端编码员,我的 CSS 技能有点弱.当我参与布局时,我倾向于使用基于表格的格式,因为多年来我的思想已经被基于表格的滥用所扭曲.有一个特别的问题我总是被绊倒.什么是最好的 CSS 替代品:

<tr><td align="center">内容在这里</td></tr>

我有时使用:

content

但这似乎不太对.我不是要对齐文本,而是要对齐内容.此外,这似乎对封闭元素的文本对齐有影响,需要进行调整才能修复.我不明白的一件事是:为什么没有 float:center 样式?这似乎是最好的解决方案.希望我遗漏了一些东西,并且有一种完美的 CSS 方法可以做到这一点.

解决方案

您说得对,text-align 用于对齐文本.实际上,只有 Internet Explorer 才能让您将文本以外的任何内容居中.任何其他浏览器都会正确处理这个问题,并且不会让块元素受到 text-align 的影响.

要使用 css 居中块元素,您可以使用 margin: 0 auto; 正如 Joe Philllips 建议的那样.虽然你根本不需要保留桌子.

没有 float: center; 的原因是浮动旨在将元素(通常是图像)放置在左侧或右侧,并让文本围绕它们流动.在这种情况下,在中心浮动某些内容没有意义,因为这意味着文本必须在元素的两侧流动.

I prefer working with CSS based design, but as more of a back end coder my CSS skills are a bit weak. When I get involved with layout, I tend to fall back on table based formatting because my mind has been warped by years of table based abuse. There's one particular problem that I always trip over. What is the best CSS alternative to:

<table width="100%">
    <tr>
        <td align="center">
            content goes here
        </td>
    </tr>
</table>

I sometimes use:

<div style="width:100%; text-align:center">content</div>

But this doesn't seem quite right. I'm not trying to align text, I'm trying to align content. Also, this seems to have an effect on the text alignment of enclosed elements, which requires tweaking to fix. One thing I don't get is: why isn't there a float:center style? It seems like that would be the best solution. Hopefully, I'm missing something and there is a perfect CSS way to do this.

解决方案

You are right that text-align is intended for aligning text. It's actually only Internet Explorer that lets you center anything other than text with it. Any other browser handles this correctly and doesn't let block elements be affected by text-align.

To center block elements using css you use margin: 0 auto; just as Joe Philllips suggested. Although you don't need to keep the table at all.

The reason that there is no float: center; is that floating is intended to place elements (typically images) either to the left or the right and have text flow around them. Floating something in the center doesn't make sense in this context as that would mean that the text would have to flow on both sides of the element.

这篇关于CSS 使内容居中的适当方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆