使用带自动保证金的calc [英] using calc with auto margin

查看:111
本文介绍了使用带自动保证金的calc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过使用css3 calc()使用margin-right来自动添加一些像素,但似乎该语句是错误的。

I wanted to use margin-right to auto + some pixels by using css3 calc() but seems the statement is wrong.

selector{margin: calc(auto + 5px);

那么,如何使用它以便获得自动边距并加上固定的像素边距?

So, how can use so that it can take auto margin and plus fixed pixels margin?

像这样的东西!

推荐答案

看着我今天有一个问题,我感到feel愧,为什么我不能正确地思考呢?基本上,自动页边距就是剩下的边距减去div宽度的50%。在此基础上,我们可以像这样布置元素:

Looking at my own question today, I feel ashamed why I couldn't think it correctly? Basically, auto margin is what left margin 50% minus width of the div. In this basis, we can layout the element like this:

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

使用前面的代码等效于 calc(auto + 5px); 。由于calc不支持自动,因此我们需要考虑实际的翻译概念。这意味着我们也可以使用 50%-宽度的一半的绝对位置进行布局,但是我喜欢 transform

Using the preceding code is equivalent to calc(auto + 5px);. Since, calc doesn't support auto we need to trick with actual concept of translation. This means we can also layout with absolute position with the concept of 50% - half of width, but I like transform here for simplicity.

请参见以下演示:

.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>

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

Increase or decrease the plus minus value of left and right to understand it correctly.

注意:请使用以下内容代码

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

与使用相同:

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

此概念。

还要注意,该问题与某个百分比计算值加上所需的偏移量有关。因此,在此答案中,同时使用了calc和transform。如果您确实需要在中间移动,那么我们可以使用(不带左边距或右边距):

Also note that the question is related to some percentage calculation plus minus desired shift. So in this answer, it has both calc and transform is used. If you exactly require to shift at middle then we could just use (without margin-left or margin-right):

transform: translateX(-20px)

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

The answer is provided with 50% calc but the question was requiring to use some percentage like calc(20% - 20px).

这篇关于使用带自动保证金的calc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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