CSS 数据类型

CSS 数据类型 <length-percentagenotransR 表示的值可以是 <length><percentage>

语法

<length-percentage> = <length> | <percentage> 

CSS <length-percentage>: 基本示例

在以下示例中,<length-percentage> 数据类型用于设置内容区域的左边距和侧边栏的宽度,从而实现具有相对于父容器的特定百分比的响应式布局设计。

<html>
<head>
<style>
   body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
   }
   header {
      background-color: #333;
      color: white;
      text-align: center;
      padding: 20px 0;
   }
   .sidebar {
      float: left;
      width: 25%; /* 使用基于百分比的宽度 */
      background-color: #f0f0f0;
      padding: 20px;
   }
   .content {
      margin-left: 20%; /* 匹配侧边栏的宽度 */
      padding: 20px;
   }
   footer {
      clear: both;
      background-color: #333;
      color: white;
      text-align: center;
      padding: 10px 0;
   }
</style>
</head>
<body>
<header>
   <h1>Header</h1>
</header>
<div class="sidebar">
   <h2>Sidebar</h2>
   <p>This is the sidebar content.</p>
</div>
<div class="content">
   <h2>Main Content</h2>
   <p>This is the main content area.</p>
   <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
</div>
<footer>
   <p>© 2023 Website</p>
</footer>
</body>
</html> 

CSS <length-percentage> - 使用于calc()

以下示例演示了如何使用 calc() 函数,其中百分比被解析为长度。

<html>
<head>
<style>
   /* Using length-percentage data type within calc() */
   .container {
      display: flex;
   }
   .left {
      width: calc(30% - 20px); /* 30% width minus 20px gap */
      height: 20px;
      background-color: red;
      padding: 10px;
   }
   .right {
      flex: 1;
      background-color: blue;
      padding: 10px;
   }
</style>
</head>
<body>
<div class="container">
   <div class="left"></div>
   <div class="right"></div>
</div>
</body>
</html>