问题
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.
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>
https://jsfiddle.net/xm2gvzbf/5/
回答1:
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.
For an illustration see this revised demo, which has an added border around .container
.
If you reduce the width of .container
you'll see the centering work. Here's a second revised demo with width: 50%
applied to .container
.
回答2:
It actually works, but without specifying the width it takes full 100%. Try something like:
.container {
margin: 0 auto;
width:50%;
}
Hope this may help
回答3:
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.
回答4:
You should set a width on .container
to let the margin: 0 auto;
work. See the updated JSfiddle.
来源:https://stackoverflow.com/questions/35817096/css-margin-0-auto-not-centering