div高度为body宽度一半 - pod4g/tool GitHub Wiki

问题

请使用纯css实现

  1. div垂直居中与body
  2. .container的高度为body高度的一半
  3. 字符A垂直居中于div
<body>
 <div class="container" style="width: 100px; font-size: 20px">A</div>
</body>

实现一:使用vw

* {margin: 0; padding: 0}

html, body { height: 100% }

body { position: relative }

.container {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: red;
  height: 50vw;
  display: flex;
  aligin-items: center;
}

实现二:使用padding和calc

关键点在于:padding不管是设置上下还是左右百分比值,其参考的都是父容器的width

基于上述技巧,可以实现纯css的响应式正方形

* {margin: 0; padding: 0}

html, body { height: 100% }

body { position: relative }

.container {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: red;
  display: flex;
  aligin-items: center;
  /* 设置为1,让其高度等于font-size,这样就可以用calc了 */
  line-hegiht: 1;
  // 因为line-height = 1,故其`A`字符的高度即为`font-size`,即20px,上下平分这20px,所以都要减去10px
  padding-top: calc(25% - 10px);
  padding-bottom: calc(25% - 10px);
}
⚠️ **GitHub.com Fallback** ⚠️