我想通过使用css3 calc()来使用margin-right来自动+一些像素,但似乎声明是错误的.
selector{margin: calc(auto + 5px);
Run Code Online (Sandbox Code Playgroud)
那么,如何使用它可以获取自动边距和加固定像素边距?
像这样的东西!
Mr.*_*ien 13
来自MDN:
的计算值()函数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
;
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅文档
当你评论说,要居中的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;
}
Run Code Online (Sandbox Code Playgroud)
Bho*_*yar 13
今天看到自己的问题,很惭愧,怎么就想不通了?基本上,自动边距是左边距减去 div 宽度的 50%。在此基础上,我们可以这样布局元素:
margin-left: calc(50% + 5px);
transform: translateX(-50%);
Run Code Online (Sandbox Code Playgroud)
使用前面的代码等效于calc(auto + 5px);
. 由于 calc 不支持 auto 我们需要用实际的翻译概念来欺骗。这意味着我们也可以使用 的概念进行绝对位置布局50% - half of width
,但transform
为了简单起见,我喜欢这里。
请参阅下面的演示:
margin-left: calc(50% + 5px);
transform: translateX(-50%);
Run Code Online (Sandbox Code Playgroud)
.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;
}
Run Code Online (Sandbox Code Playgroud)
增加或减少左右的正负值才能正确理解。
注意:使用下面的代码
.right{
margin-left: calc(50% + 20px);
transform: translateX(-50%);
}
Run Code Online (Sandbox Code Playgroud)
与使用相同:
.right{
margin-right: calc(50% - 20px);
transform: translateX(-50%);
}
Run Code Online (Sandbox Code Playgroud)
对于这个概念。
另请注意,该问题与某些百分比计算加减所需偏移有关。所以在这个答案中,它同时使用了 calc 和 transform 。如果您确实需要在中间移动,那么我们可以使用(没有 margin-left 或 margin-right):
transform: translateX(-20px)
Run Code Online (Sandbox Code Playgroud)
答案提供了 50% 的计算,但问题是需要使用一些百分比,例如calc(20% - 20px)
.
归档时间: |
|
查看次数: |
18258 次 |
最近记录: |