CSS 媒体特性 - 高度



CSS 媒体特性 height 用于根据视口的高度应用不同的样式。

height 媒体特性也可以与 min-heightmax-height 属性一起使用,以指定视口的最小和最大高度。

可能的值

  • <length> − 视口的高度由特定的长度值表示,例如像素 (px) 等。

语法

height: <length>

CSS height - length 值

以下示例演示了如果 height 媒体特性的值为 150px,则元素的背景颜色将更改为紫色,否则背景颜色将保持白色:

<html>
<head>
<style>
   iframe {
      display: block;
   }
</style>
</head>
<body>
   
   <label id="labelHeight" for="width">Height:150</label>
   <input id="height" name="height" type="range" min="120" max="200" step="5" value="150" />
   
   <iframe
   id="block"
   srcdoc="<style> @media (height: 150px) { div { background:violet; } } </style><div>To see the effect resize your viewport's height.</div>">
   </iframe>
      
   <script>
      const updateSize = (size, label) => {
         block.style[size] = `${eval(size).value}px`;
         label.textContent = `${size}: ${eval(size).value}`;
      };
      height.oninput = () => updateSize("height", labelHeight);
   </script>
</body>
</html>   

CSS height - max-height 属性

以下示例演示了当视口的高度为 170px 或更小时,盒元素的背景颜色将更改为浅绿色,否则背景颜色将保持白色:

<html>
<head>
<style>
   iframe {
      display: block;
   }
</style>
</head>
<body>
   
   <label id="labelHeight" for="width">Height:150</label>
   <input id="height" name="height" type="range" min="120" max="200" step="5" value="150" />
   
   <iframe
   id="block"
   srcdoc="<style> @media (max-height: 170px) { div { background: lightgreen; } } </style><div>To see the effect resize your viewport's height.</div>">
   </iframe>
      
   <script>
      const updateSize = (size, label) => {
         block.style[size] = `${eval(size).value}px`;
         label.textContent = `${size}: ${eval(size).value}`;
      };
      height.oninput = () => updateSize("height", labelHeight);
   </script>
</body>
</html>  

CSS height - min-height 属性

以下示例演示了当视口的高度大于 140px 时,盒元素的背景颜色将更改为浅绿色,否则背景颜色将保持白色:

<html>
<head>
<style>
   iframe {
      display: block;
   }
</style>
</head>
<body>
   
   <label id="labelHeight" for="width">Height:150</label>
   <input id="height" name="height" type="range" min="120" max="200" step="5" value="150" />
   
   <iframe
   id="block"
   srcdoc="<style> @media (min-height: 140px) { div { background: lightgreen; } } </style><div>To see the effect resize your viewport's height.</div>">
   </iframe>
      
   <script>
      const updateSize = (size, label) => {
         block.style[size] = `${eval(size).value}px`;
         label.textContent = `${size}: ${eval(size).value}`;
      };
      height.oninput = () => updateSize("height", labelHeight);
   </script>
</body>
</html>  
广告