如何中心的东西 - display:block / inline-block [英] How to center things - display:block/inline-block

查看:205
本文介绍了如何中心的东西 - display:block / inline-block的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在html和css中居中时,我发现有两种方法 - 或者在元素上应用:

When centering things in html and css, I find two approaches - either applying on the element :

display:block;
margin:0 auto;

或使用:

display:inline-block;
text-align:center; (on the parent element)

我总是想知道哪个更好,为什么。

I always wonder which is better and why. Thanks!!

推荐答案

这是一个经典且重要的问题。

This is a classic and important question.

元素可以是内联的(意味着它们都彼此相邻 - 比如一个span标签),也可以是块(意味着堆叠在一起,就像一个div标签)。

Elements can either be inline (meaning they all sit next to each other - like a span tag) or they can be block (meaning the stack up on top of each other - like a div tag).

边距:自动,当你第一次看到它有点奇怪,是最好的和唯一的方法来集中块级别(位置静态),元素。

Margin: auto, while a bit odd when you first see it, is the best and only way to center a block level (position static), element.

对于任何显示:inline(像一个span标签) - 只有中心的方式是如果你指定text-align:center在父上。这将使所有显示的内容显示在其中:position:static;

For anything that is display: inline (like a span tag) - the only way to center it is if you specify text-align: center on the parent. This will center everything display: inline inside it that is position: static;

显示:inline-block是两者的混合体, > new(但是如果你使用在另一个答案中提到的hack,则支持远离ie7)。使用inline-block,你可以得到inline的好处,你可以把一堆东西放在一起,让它们全部居中(考虑一个nav,其中所有导航项都在中心),但也有

Display: inline-block is a hybrid of the two that is relatively new (but supported as far back as ie7 if you use the hack mentioned in another answer). With inline-block, you get the benefits of inline, in that you can you stick a bunch of things next to each other and have them all be centered (think of a nav where all nav items are all centered), but ALSO have each item take advantage of some of the stuff you get with display: block - the most important one being HEIGHT.

想象一个场景,其中每个导航项目有一个背景图像,它是一个80px高 - 你不能使一个内联元素的高度为80 - 所以你必须使每个元素显示:块 - 只有这样,你可以给它一个高度。所以为了使它们彼此相邻,你会浮动它们。问题是如果你浮动他们,你不能让他们都在页面的中心,除非你给一个固定的宽度nav和margin:auto THAT。这意味着导航具有固定的宽度 - 可能没问题,但有时导航必须有动态元素,不同语言的不同宽度等。

Imagine a scenario where each nav item has a background image that is 80px tall - you can't make an inline element have a height of 80 - so you'd have to make each element display: block - only then can you give it a height. So to make them all appear next to each other, you'd float them. The problem is if you float them, you can't have them all be centered on the page unless you give a fixed width to the nav and margin: auto THAT. This means the nav has a fixed width - might be okay, but there are times when the nav has to have dynamic elements, different widths for different languages, etc.

Enter display:inline-block。

Enter display: inline-block.

这篇关于如何中心的东西 - display:block / inline-block的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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