首页 > 解决方案 > 为什么以百分比表示的元素高度不起作用?

问题描述

我试图创建一个响应式正方形并添加了以下内容:

.square {
  width: 50%;
  height: 50%;
}

但是,它水平扩展但垂直根本不扩展......

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  
  <style>
    body{
      background: #cccede;
      
    }
    

    .square {
  width: 50%;
  height: 50%;
       border: 2px solid black
}
  </style>
</head>
<body>

  <div class="square"></div>

</body>
</html>

在这个片段中,为什么盒子不使用窗户的高度来计算它的高度?

标签: css

解决方案


height: 50% means that it will be half as tall as its parent container. Your square is that small because it's inside the body tag which is small. You can make the body as tall as the screen by doing this:

body {
    height: 100%;
}

推荐阅读