我可以将 auto 值与 calc() 属性一起使用吗?

新手上路,请多包涵

我想使用 calc() margin 将 --- 设置为 auto 加上一些像素量,但我的代码似乎不起作用。

 selector {
    width: 200px;
    height: 200px;
    margin-left: auto;
    margin-right: auto;
    background: red;
    margin: calc(auto + 5px);
}
 <div></div>

我可以将 calc() 设置为自动边距加固定值吗?像这样的东西:

在此处输入图像描述

原文由 Bhojendra Rauniyar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 872
2 个回答

今天看到自己的问题,我为自己为什么不能正确思考而感到羞愧?基本上,自动边距是左边距 50% 减去 div 的宽度。在此基础上,我们可以这样布局元素:

 margin-left: calc(50% + 5px);
transform: translateX(-50%);

使用前面的代码相当于 calc(auto + 5px); 。由于 calc 不支持 auto 我们需要用实际的翻译概念来欺骗。这意味着我们也可以使用 50% - half of width 的概念进行绝对位置布局,但为了简单起见,我喜欢 transform

请看下面的演示:

 .parent{
  position: relative;
}
.child{
  border: 2px solid green;
  width: 25%;
  height: 50px;
  margin: 10px auto;
}
.right{
  margin-left: calc(50% + 20px);
  transform: translateX(-50%);
}
.left{
  margin-left: calc(50% - 20px);
  transform: translateX(-50%);
}
#border{
  height: 100%;
  border: 1px solid yellow;
  width: 25%;
  margin: auto;
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
  right: 0;
}
 <div class="parent">
  <div id="auto" class="child">
    auto margin
  </div>
  <div id="auto-right" class="child right">
    auto + pushed to right
  </div>
  <div class="child left">
    auto + pushed to left
  </div>
  <div id="border"></div>
</div>

增加或减少左右的正负值以正确理解。

注意: 使用下面的代码

.right{
  margin-left: calc(50% + 20px);
  transform: translateX(-50%);
}

与使用相同:

 .right{
  margin-right: calc(50% - 20px);
  transform: translateX(-50%);
}

对于这个概念。

另请注意,该问题与某些百分比计算加上减去所需的班次有关。所以在这个答案中,它同时使用了 calc 和 transform 。如果您确实需要在中间移动,那么我们可以使用(没有左边距或右边距):

 transform: translateX(-20px)

答案提供了 50% 的计算,但问题是需要使用一些百分比,例如 calc(20% - 20px)

原文由 Bhojendra Rauniyar 发布,翻译遵循 CC BY-SA 4.0 许可协议

来自 MDN

The calc() CSS function can be used anywhere a <length> , <frequency> , <angle> , <time> , <number> , 或 <integer> 是必需的。使用 calc(),您可以执行计算以确定 CSS 属性值。

不能在那里使用 auto ,因为它不是 calc() 的有效值。

calc()

 term
  : unary_operator?
    [ NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* | ANGLE S* |
      TIME S* | FREQ S* ]
  | STRING S* | IDENT S* | URI S* | hexcolor | function | math
  ;

有关更多信息,请参阅 文档


As you commented that you want to center the div but you also want a 5px margin on the right than you can achieve it by在父元素上使用 text-align: center; 并使子元素 div 元素为 display: inline-block;

演示

输出

在此处输入图像描述

div.wrap {
    text-align: center;
}

div.wrap div {
    display: inline-block;
    height: 100px;
    width: 100px;
    color: #fff;
}

div.wrap div.with_margin {

    margin-right: 5px;
    background: #f00;
}

div.wrap div.without_margin {
    background: #000;
}

原文由 Mr. Alien 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题