教程 css tutorial

calc() 函数

calc() 是 CSS 中的计算工具函数,允许将不同单位的值进行加减乘除操作,常用于布局中动态尺寸的设定。

1. 基本语法

css
width: calc(100% - 40px);

可用运算符包括:

  • + 加
  • - 减
  • * 乘
  • / 除(仅限数字,不能除单位)

注意:运算符两侧必须留空格,如 calc(100% - 10px)。

2. 常见用途

示例 1:固定间距减去动态宽度

css
.sidebar {
  width: calc(100% - 200px); /* 减去主内容宽度 */
}

示例 2:垂直居中元素

css
.box {
  position: absolute;
  top: calc(50% - 50px); /* 元素高度为 100px */
}

示例 3:输入框和按钮组合

css
.input {
  width: calc(100% - 100px); /* 按钮宽度为 100px */
  float: left;
}

calc() 函数示例

在线代码演示
源码
<!DOCTYPE html>
<html lang="zh-CN">

<head> <meta charset="UTF-8" /> <title>calc() 函数示例</title> <style> body { font-family: sans-serif; padding: 40px; }

.container {
  background-color: #fff9c4;
  padding: 20px;
  border-radius: 8px;
  width: 100%;
  box-sizing: border-box;
}

.search-bar {
  display: flex;
}

.search-input {
  width: calc(100% - 120px);
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-right: none;
  border-radius: 4px 0 0 4px;
}

.search-button {
  width: 120px;
  background-color: #ffb74d;
  border: none;
  font-size: 16px;
  color: white;
  cursor: pointer;
  border-radius: 0 4px 4px 0;
}

</style> </head>

<body> <div class="container"> <div class="search-bar"> <input class="search-input" type="text" placeholder="请输入关键字…" /> <button class="search-button">搜索</button> </div> </div> </body>

</html>