如何使用 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
How to center multiple inline-block elements with 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
回答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
.