【问题标题】:Why do I get a different result from setting translate to -50% and setting margins to 50%?为什么将转换设置为 -50% 并将边距设置为 50% 会得到不同的结果?
【发布时间】:2016-09-12 05:08:18
【问题描述】:

假设父级是相对的,子级(style-x)是绝对的。我用前 50%,剩下的 25% 让孩子居中。

我希望实际上将孩子居中,所以我设置了 transform: translate(-50%, -50%)。我不确定这是否居中,所以我通过删除该行并添加'margin-top:-55px;'来仔细检查(高度的一半)和'margin-left:-45px;' (宽度的一半)。

这两行将我的元素定位在稍微不同的位置,但这与我的 CSS 模型不同。怎么回事?

body {
  height: 100%;
  width: 100%;
  margin: 0 auto;
}
#main {
  overflow: auto;
  height: 64vh;
  width: 38vw;
  margin: 0 auto;
  margin-top: 10%;
  position: relative;
  border: 1vh solid black;
  overflow: hidden;
}
#style-x {
  /*Why doesn't translate(-50%, -50%) give me 
      the same position as setting the margin top and
      left to half of the width and height?*/
  width: 90px;
  height: 110px;
  /*
      transform: translate(-50%, -50%);*/
  margin-top: -55px;
  margin-left: -45px;
  position: absolute;
  top: 50%;
  left: 25%;
  padding: 2%;
  text-align: center;
  background: green;
}
#left-col {
  float: left;
  width: 4%;
  height: 101%;
  margin-left: 46%;
  background: black;
}
#right-col {
  float: left;
  width: 4%;
  height: 101%;
  margin: 0 auto;
  margin-left: 0;
  background: black;
}
<body>
  <section id='main'>
    <div id='style-x'>X</div>
    <div id='left-col'></div>
    <div id='right-col'></div>
    </section>
</body>

如果您想要可视化,这是我的 Codepen。

http://codepen.io/sentedelviento/pen/ORyqzv

【问题讨论】:

  • 所以您希望style-xsection 中水平和垂直居中?只需删除边距并添加您拥有的translate 并使left 50%
  • 你没有粘贴 codepen 链接
  • 谢谢,已修复。为什么要删除边距?为什么不把翻译拿出来?我想把它放在部分的左半部分。

标签: css


【解决方案1】:

你的方法没有问题。两者都将尝试根据您提供的值居中。

margin 方法失败,因为您没有像这样使用Box Sizing method

box-sizing: border-box

这会导致所有元素大于指定的高度和宽度。没有这个,你告诉浏览器在宽度和高度上添加任何填充或边框。

因此,当使用边距方法时,您的较大元素会发生变化。

您在style-x 上设置了2% 填充,在#main 上设置了38vw 的宽度。当使用边距使事物居中时,您需要考虑这些可变值

当您设置 百分比 填充时,its calculated based on the width of the containing block

另一方面,transform 方法使用包含块的边界框,并且在较大的元素居中没有问题。

如果使用边距方法,我建议您在 mainstyle-x 上包含此 box-sizing。你可以使用

*, after, before {
  box-sizing: border-box;
}

这可以更好地控制所有元素的尺寸。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 2012-02-22
    • 2020-11-02
    • 2021-02-25
    • 2021-03-25
    • 2020-07-30
    • 1970-01-01
    相关资源
    最近更新 更多