CSS 使用 Margin Auto 和 Center 将 Float Left Div 居中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2439177/
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
Use Margin Auto and Center to center Float Left Div
提问by Cheok Yan Cheng
I know this question had been asked many times.
我知道这个问题已经被问过很多次了。
However, I follow their suggestion :
但是,我遵循他们的建议:
<center>
<div style="margin : auto; text-align: center">
<a href="#" style="float: left; margin-right: 10px;">Menu Item 1</a>
<a href="#" style="float: left; margin-right: 10px;">Menu Item 2</a>
<a href="#" style="float: left; margin-right: 10px;">Menu Item 3</a>
</div>
</center>
(source: google.com)
(来源:google.com)
By using "Center" and "Margin Auto", "Text Align Center" ... I still unable to center the menu item.
通过使用“居中”和“自动边距”、“文本居中对齐”......我仍然无法将菜单项居中。
回答by Cheok Yan Cheng
use inline-block instead of float left.
使用内联块而不是向左浮动。
<center>
<div style="margin : auto; text-align: center">
<a href="#" style="display: -moz-inline-box; display: inline-block; left; margin-right: 10px;">Menu Item 1</a>
<a href="#" style="display: -moz-inline-box; display: inline-block; margin-right: 10px;">Menu Item 2</a>
<a href="#" style="display: -moz-inline-box; display: inline-block; margin-right: 10px;">Menu Item 3</a>
</div>
</center>
回答by Chris
Why not use an unordered list? After all, you are creating a list of links.
为什么不使用无序列表?毕竟,您正在创建一个链接列表。
<ul>
<li><a href="#">Menu Item 1</a></li>
<li><a href="#">Menu Item 2</a></li>
<li><a href="#">Menu Item 3</a></li>
</ul>
li {
display: inline;
}
ul {
width: 50%;
margin: 0 auto;
}
回答by Pekka
Your code works fine, but the div
is 100% wide by default so you won't notice any centering.
您的代码工作正常,但div
默认情况下为 100% 宽,因此您不会注意到任何居中。
Either give the div
a width (fixed in pixels or relative in percent) or, if you just want to center the menu items, give the div a text-align
setting:
要么给div
一个宽度(固定像素或相对百分比),或者,如果你只想居中菜单项,给 div 一个text-align
设置:
<div style="margin : auto; text-align: center">
回答by Dmitriy Yusupov
Work for me (not used float, only text-align): http://jsfiddle.net/vnAvk/20/
为我工作(不使用浮动,只使用文本对齐):http: //jsfiddle.net/vnAvk/20/
<div class="a">
<p>A div Hello</p>
<p class="center">
<a class="b">B Div hello</a>
<a class="c">C Div Hello</a>
<a class="d">D div Hello</a>
<a class="e">E div Hello</a>
</p>
</div>
div.a { border: 1px solid red;}
p.center { text-align: center; }
a.b { border: 2px solid blue; }
a.c { border: 2px solid green; }
a.d { border: 2px solid black; }
a.e { border: 2px solid yellow; }