【问题标题】:CSS calc() Why is 100% = width of parent element and not the width of the actual element [duplicate]CSS calc()为什么100%=父元素的宽度而不是实际元素的宽度[重复]
【发布时间】:2018-03-13 16:16:55
【问题描述】:

我正在尝试在 CSS 中使用 calc() 创建一个简单的文本滑块,但它不起作用。

为了展示它应该如何工作,我另外添加了正确的值

编辑:
我已经编辑了代码,它现在应该不再包含错误,但它仍然不起作用。
calc() 中的 100% 似乎是指父元素。
我该如何解决这个问题?

.box {
  width: 200px;
  height: 30px;
  line-height: 30px;
  font-family: arial;
  font-weight: bold;
  color: #FFF;
  background: #000;
  overflow: hidden;
  cursor: default;
  -moz-user-sselect: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.text {
  white-space: nowrap;
  float: left;
  padding: 0 7px;
  box-sizing: border-box;
  transition: margin 0.5s linear;
  background: #404040;
}

.a:hover {
  transition: margin 2s linear;
  margin: 0 0 0 -90.25px;
}

.b:hover {
  transition: margin 2s linear;
  margin: 0 0 0 calc(200px - 100%);
}
<div class="box">
  <div class="text a">Dieser Text ist zu groß für diese Box</div>
</div>
<br>
<div class="box">
  <div class="text b">Dieser Text ist zu groß für diese Box</div>
</div>

【问题讨论】:

  • 定义“它不工作” 它什么都不做,有意想不到的结果,召唤一个恶魔?请描述预期结果和实际结果
  • idk 如果这是问题所在,但我认为你应该写这个:margin: 0 0 0 calc(200px-100%)
  • 代码很好 200px - 100% (100% = width = 200px) = 0,所以你将边距设置为 0
  • 应该是 100% 而不是文本元素的宽度?

标签: html css


【解决方案1】:

如果运算符周围没有空格,则 calc 中的表达式将不起作用。 margin: calc(200px - 100%); 应该可以工作。

【讨论】:

    【解决方案2】:

    你错过了calc里面的空格

    您应该使用margin: calc(200px - 100%) 而不是margin: calc(200px-100%)

    如需进一步参考,您最好查看此link

    .box {
      width: 200px;
      height: 30px;
      line-height: 30px;
      font-family: arial;
      font-weight: bold;
      color: #FFF;
      background: #000;
      overflow: hidden;
      cursor: default;
      -moz-user-sselect: none;
      -webkit-user-select: none;
      -ms-user-select: none;
      user-select: none;
    }
    
    .text {
      white-space: nowrap;
      float: left;
      padding: 0 7px;
      box-sizing: border-box;
      transition: margin 0.5s linear;
      background: #404040;
    }
    
    .text:hover {
      transition: margin 2s linear;
      margin: 0 0 0 -90.25px; //<-this should be the result of calc.
      margin: calc(200px - 100%); //<-why does this not work?
    }
    <div class="box">
      <div class="text">Dieser Text ist zu groß für diese Box</div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-07
      • 2021-08-13
      • 2023-01-13
      • 2014-07-12
      • 1970-01-01
      • 2015-11-16
      相关资源
      最近更新 更多