我想使用 设置margin
为auto
加上一些像素量calc()
,但我的代码似乎不起作用。
selector {
margin: calc(auto + 5px);
}
我可以设置calc()
为自动保证金加上一个固定值吗?像这样的东西:
来自MDN:
calc() CSS 函数可以在任何需要
<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
;
有关更多信息,请参阅文档
正如您所评论的那样,您想要居中,div
但您还想要一个5px
margin
,而right
不是您可以通过使用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;
}
今天看到自己的问题,我为自己为什么不能正确思考而感到羞愧?基本上,自动边距是左边距 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)
.