CSS&"margin:0 auto&"不居中 [英] CSS "margin: 0 auto" not centering

查看:52
本文介绍了CSS&"margin:0 auto&"不居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我知道已经讨论了此主题.但是,我研究了各种解决方案,但对它们却收效甚微.

Okay I understand that this topic has been covered. But I have looked at various solutions and have had little success with them.

我不知道为什么此 margin:0 auto; 无法正常工作.我尝试用 width:calc(33%-40px); 来补偿填充,但这没用.

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/

推荐答案

正在运行.

问题是您将 div 居中放置,默认情况下它是块级元素,因此占用其父对象( body ,在这种情况下).因此,没有水平移动的空间,因此也没有居中的空间.

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.

有关说明,请参见此 修订的演示 ,其中已添加了 .container 周围的边框.

For an illustration see this revised demo, which has an added border around .container.

如果减小 .container 的宽度,则会看到居中的效果.这是第二个 修订的演示 ,其 width:50%应用于 .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.

这篇关于CSS&"margin:0 auto&amp;"不居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆