在响应宽度上使用 calc() 到中心元素

Bun*_*fin 3 css

是否可以使用 calc() 将宽度用 % 定义的元素居中?

例如

.wrapper {
  width: 100%;
  background-color: black;
  height: 300px;
  position: absolute;
  top: 0;
}
.inside {
  width: 100%;
  margin-left: 30px;
  background-color: yellow;
  height: 250px;
  margin: 20px;
}
.inside h1 {
  width: 30%;
  background-color: white;
  text-align: center;
}
.inside h1 {
  position: absolute;
  left: calc(50% - 15%);
  left: -webkit-calc(50% - 15%);
}
Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
  <div class="inside">
    <h1>CENTERED to viewport</h1>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

滑块

这是滑块。它有一个“字符串”,引导滑块的步骤,并且标题始终位于屏幕中间。但出于设计目的,该线从右侧开始一点,向左结束一点,宽度为 80%。顶部是带绳子的 1 号滑块,第二个滑块同步的是带有大白色方块的区域。

也许现在更清楚了,为什么我要尝试我所尝试的事情。

Hud*_*nPH 5

是的,如果您在 css 中创建一个变量,例如:

<!DOCTYPE html>
<html>
<head>
<style>
#div1 {
    --Example: 200px;
    position: absolute;
    left: 50px;
    width: calc(100% - var(--Example)/2);
    border: 1px solid black;
    background-color: yellow;
    padding: 5px;
    text-align: center;
}
</style>
</head>
<body>

<div id="div1">Some text...</div>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)