如何使用 CSS 将多个内联块元素居中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8748654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:34:03  来源:igfitidea点击:

How to center multiple inline-block elements with CSS?

css

提问by JoJo

I want to horizontally center two (or possibly more) inline-block elements inside a container block element. It should look like this:

我想在容器块元素内水平居中两个(或可能更多)内联块元素。它应该是这样的:

--------------------------
|      _____   _____      |
|     |     | |     |     |
|     | foo | | bar |     |
|     |_____| |_____|     |
|_________________________|

However, with my broken code, it is currently looking like this:

但是,使用我损坏的代码,它目前看起来像这样:

--------------------------
| _____   ____            |
||     | |     |          |
|| foo | | bar |          |
||_____| |_____|          |
|_________________________|

HTML

HTML

<div>
 <a>foo</a>
 <a>bar</a>
</div>

CSS

CSS

div a {
 display: inline-block;
 padding: 1em;
 margin: 1em;
 border: 1px solid black;
}

The reason why the two anchors have to be inline-block and not just plain inline is because I don't want the anchor's padding and margin to overlap.

两个锚点必须是 inline-block 而不仅仅是普通内联的原因是因为我不希望锚点的填充和边距重叠。

回答by Jakub

Simply set text-align: center;on the div container.

只需text-align: center;在 div 容器上设置即可。

回答by Nate B

Set text-align: center;on the parent element.

text-align: center;在父元素上设置。

回答by Maksim Vi.

have you tried the following?

你试过以下吗?

div{
   text-align:center;
}

回答by Daniel Nyamasyo

Either you can try these one

你可以试试这些

div{
   text-align:center;
}

or set margin auto as shown below

或设置自动边距,如下所示

div a{
  margin:auto;
  margin-left:1em;
  margin-right:1em;
  margin-top:1em;
  margin-bottom:1em;
 display:inline-block;
}

A good example is shown here

这里显示一个很好的例子

回答by Hyman Mason

I used text-align: "center"in the parent container, and that centered the ULs on the page, but it also centered the text in the ULs (not desired). So I added a text-align: "left"to the <ul>so that the text was next to the list-style.

text-align: "center"在父容器中使用,并将 UL 在页面上居中,但它也将 UL 中的文本居中(不需要)。所以我text-align: "left"在 the 中添加了一个,<ul>这样文本就在list-style.