如何在 CSS 中设置 Calc 视口单位?

cssweb developmentfront end technology更新于 2024/8/3 13:32:17

在本文中,我们将重点介绍如何在 CSS 中设置 cal() 函数以设置视口单位。

在 HTML 页面中,将值应用于 CSS 属性时,计算是通过使用 calc() 函数执行的。

calc() 函数会执行一个值,用作属性值并用于进行重要的数学运算。calc() 函数的唯一可用位置是在值中。

calc() 函数将边界视为一个单独的表达式。值是该表达式的结果。事实上,即使是表达式也是遵循优先级规则的多个运算符的组合。

  • + 加法
  • - 减法
  • * 乘法。任何参数都应该是数字
  • / 除法。右侧应该是一个数字

语法

以下是 calc() 函数的语法 -

element {
   // CSS property
   property : calc( expression) 
}

编写语句时应谨慎,并应处理以下位置。

  • + 和 - 符号应该用空白区域包围,例如 height(100%-30px) 被视为无效,而 height(100% - 30px) 是有效表达式。对于/和*管理员,白色分隔并非必需,但强烈建议使用。

  • 除以0会导致错误。

示例

在此程序中,我们将使用内部CSS设置calc透视单位的解决方法,我们将像往常一样导入此CSS,就像我们在基本版本中所做的那样。此外,在正文中,添加一个division标签和一个heading标签,其中包含带有类的消息。在这里,我们使用calc()函数将div元素的宽度改变90px并显示结果。

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>
         Set Calc Viewport Units Workaround in CSS 
      </title>
      <style>
         body {
            background-color:skyblue;
         }
         div {
            /* Using the calc() func to change the
            width of the div element by 90px */
            width: calc(90% - 90px);
            border: 1px solid black;
            background-color: white;
            margin-top: 50px;
            text-align: center;
         }
      </style>
   </head>
   <body>
      <div>
         <h1>Set Calc Viewport Units Workaround in CSS Using Cal() Function</h1>
      </div>
   </body>
</html>

示例

在此程序中,我们将使用内部 CSS 设置计算透视单位的解决方法,并将此 CSS 像通常一样导入,用于基本版本。此外,在正文中,添加一个 division 标签和一个 heading 标签,其中包含带有类的消息。在这里,我们使用 calc() 函数来更改 h1 组件的文本大小并显示结果。

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>
         Set Calc Viewport Units Workaround in CSS Using Calc() Function
      </title>
      <style>
         body {
            background-color: skyblue;
         }
         h1 {
            color: red;
            /* Using the calc() func to change
            the font size of the h1 element */
            font-size: calc(1.2rem + 2vw);
         }
         div {
            width: calc(100% - 100px);
            border: 1px solid black;
            background-color: white;
            margin-top: 50px;
            text-align: center;
         }
      </style>
   </head>
   <body>
      <div>
         <h1> Set Calc Viewport Units Workaround in CSS Using Calc() Function</h1>
      </div>
   </body>
</html>

示例

支持的浏览器 − pointer-events 属性支持的浏览器列表如下 −

  • Google Chrome 1.0
  • Edge 12.0
  • Internet Explorer 11.0
  • Firefox 1.5
  • Opera 9.0
  • Safari 4.0

本文重点介绍如何使用 CSS 规范中的 calc() 函数在 CSS 中设置计算视口单位的解决方法。


相关文章


有用资源