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>
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
.
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
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.
You should set a width on .container
to let the margin: 0 auto;
work. See the updated JSfiddle .
Another fix that worked for me was to change the display for the parent to display: inline in the CSS and set a max-width so that margin auto centers the text. So far, that has fixed the problem. Not sure if it's the best solution, but it's currently working. See the code below:
.parent-container{
display: inline;
max-width: 500px;
padding: 20px;
margin: 0 auto;
}
For an element which its display is block and its width is determined, we can center it horizontally with margin: sth auto; Note: If width of the element equals the width of its parent the result could not be seen.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.