使用`text-align:center`和`margin:0 auto`在CSS中将元素居中有什么区别? [英] What is the difference between using `text-align:center` and `margin: 0 auto` to center an element in CSS?

查看:93
本文介绍了使用`text-align:center`和`margin:0 auto`在CSS中将元素居中有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在很多地方都使用 margin:0 auto 来使元素居中(例如div)。

但为什么不使用 align:center
我认为以后使用它似乎更自然。

I have read in a lot of places to center elements (a div for example) using margin:0 auto.
but why not use align:center? I think it seems more natural to use the later.

另外,我们可以使用 margin 方法吗?设置垂直对齐吗?

Also, can we use margin approach to set vertical alignment too?

推荐答案

首先,没有 align:center。您在想的是文本对齐:居中,而该细节—前缀 text-—暗示了问题所在。 文本对齐属性适用于以块形式布置的嵌入式元素。当您尝试将某个块级元素居中放置在某些内容中时,内联布局样式就没有意义。

First, there is no "align: center". What you're thinking of is "text-align: center", and that detail — the prefix "text-" — is a hint as to what the problem is. The "text-align" property is for inline elements being laid out in blocks. When you're trying to center a block-level element in some content, an inline layout style does not make sense.

(现在已不推荐使用 >)元素上的align属性不是CSS东西;

The (now deprecated) align attribute on elements is not a CSS thing; it's a throwback to the days of yesteryear.

现在,关于垂直对齐,可悲的是,答案是不,至少在实际中条款。使用 margin:auto的技巧不起作用。轻率地说,仅使用CSS进行垂直对齐具有挑战性。有许多不同的情况和技术可以使用。这是一个有趣的主题页面(如果有点老的话): http:/ /www.student.oulu.fi/~laurirai/www/css/middle/

Now, as to vertical alignment, sadly the answer is "no," at least in practical terms. The trick with "margin: auto" won't work. Vertical alignment with nothing but CSS is challenging, to put it mildly. There are many different situations and techniques to use. Here's an interesting (if a little old) page on the subject: http://www.student.oulu.fi/~laurirai/www/css/middle/

从未来进行编辑—尝试进行垂直居中的任何人都应注意 flexbox的可用性布局

edit from the future — Anybody trying to do vertical centering should be keeping an eye on the availability of flexbox layout.

这篇关于使用`text-align:center`和`margin:0 auto`在CSS中将元素居中有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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