Html CSS“边距:0自动”不居中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35817096/
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
CSS "margin: 0 auto" not centering
提问by JP Foster
Okay I understand that this topic has been covered. But I have looked at various solutions and have had little success with them.
好的,我知道这个话题已经被讨论过了。但我研究了各种解决方案,但收效甚微。
I just have no clue why this margin: 0 auto;
is not working. I tried compensating the padding with width: calc(33% - 40px);
, but this did not work.
我只是不知道为什么这margin: 0 auto;
不起作用。我尝试用 补偿填充width: calc(33% - 40px);
,但这不起作用。
Any help on why this is happening, with solutions would be greatly appreciated!
任何有关为什么会发生这种情况的帮助以及解决方案将不胜感激!
.container {
margin: 0 auto;
}
[class*='col-'] {
float: left;
}
.col-2-3 {
width: 66.66%;
}
.col-1-3 {
width: 33.33%;
}
.grid:after {
content: "";
display: table;
clear: both;
}
.col-word {
width: auto;
height: auto;
padding: 25px;
border: 5px #000 solid;
border-left: 0px;
border-right: 0px;
background-color: #A7F4F6;
font-size: xx-large;
text-align: center;
}
<div class='container'>
<div class="grid">
<div class='grid'>
<div class="col-1-3">
<p class='col-word'>T</p>
<p class='col-word'>V</p>
</div>
</div>
<div class='grid'>
<div class='col-1-3'>
<div class='letter'>W</div>
</div>
<div class='col-1-3'>
<div class='letter'>P</div>
</div>
<div class='col-1-3'>
<div class='letter'>V</div>
</div>
</div>
</div>
</div>
采纳答案by Michael Benjamin
It is working.
这是工作。
The problem is you're centering a div
, which is a block-level element by default, and which therefore occupies 100% width of its parent (body
, in this case). So there's no space to move horizontally, hence no space to center.
问题是您将 a 居中div
,默认情况下它是块级元素,因此占据其父元素的 100% 宽度(body
在本例中为 )。所以没有空间可以水平移动,因此没有空间居中。
For an illustration see this revised demo, which has an added border around .container
.
有关说明,请参阅此修订后的演示,其中在 周围添加了边框.container
。
If you reduce the width of .container
you'll see the centering work. Here's a second revised demowith width: 50%
applied to .container
.
如果你减少宽度,.container
你会看到居中工作。这是第二个修改后的演示,width: 50%
适用于.container
.
回答by Alexander Bell
It actually works, but without specifying the width it takes full 100%. Try something like:
它确实有效,但没有指定宽度则需要 100%。尝试类似:
.container {
margin: 0 auto;
width:50%;
}
Hope this may help
希望这可能会有所帮助
回答by Leo The Four
You should specify the width of the div for margin:auto to work. try to use width in percentage to make your div responsive as well.
您应该为 margin:auto 指定 div 的宽度才能工作。尝试使用百分比宽度来使您的 div 也具有响应性。
回答by Roy
You should set a width on .container
to let the margin: 0 auto;
work. See the updated JSfiddle.
你应该设置一个宽度.container
让margin: 0 auto;
工作。请参阅更新的 JSfiddle。