CSS一些方法

0 阅读3分钟

5种CSS实现的垂直居中方案

  1. 使用flex布局

    • 原理flex布局提供了强大的对齐方式。通过将父元素设置为display: flex,并使用align - items: center属性可以让子元素在交叉轴(通常是垂直方向)上居中。
    • 示例代码
<style>
 .parent {
      display: flex;
      height: 200px;
      background - color: lightgray;
      align - items: center;
  }
</style>
<div class="parent">
  <div class="child">看我实现了垂直居中</div>
</div>
  • 解释:在这个例子中,.parent类对应的元素是父元素,设置为display: flex启用flex布局,height: 200px定义了父元素的高度,background - color: lightgray设置了背景颜色,align - items: center使得子元素(.child)在垂直方向上居中。

  1. 使用grid布局

    • 原理grid布局也有很好的对齐功能。将父元素设置为display: grid,然后使用place - items: center可以同时在水平和垂直方向上居中子元素。
    • 示例代码
<style>
 .parent {
      display: grid;
      height: 200px;
      background - color: lightgray;
      place - items: center;
  }
</style>
<div class="parent">
  <div class="child">看我实现了垂直居中</div>
</div>
  • 解释.parent作为父元素,display: grid开启grid布局,height: 200px确定高度,background - color: lightgray设置背景颜色,place - items: center这一属性是align - itemsjustify - items的缩写,它会将子元素在水平和垂直方向都居中。

  1. 绝对定位和transform属性

    • 原理:将子元素设置为绝对定位,然后通过top: 50%将子元素的顶部定位到父元素的中心位置,再使用transform: translateY(-50%)将子元素向上移动自身高度的一半,从而实现垂直居中。
    • 示例代码
<style>
 .parent {
      position: relative;
      height: 200px;
      background - color: lightgray;
  }
 .child {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
  }
</style>
<div class="parent">
  <div class="child">看我实现了垂直居中</div>
</div>
  • 解释:首先.parent元素设置为position: relative,为子元素的绝对定位提供相对定位的容器。height: 200px定义了父元素高度,background - color: lightgray设置背景色。.child元素是要垂直居中的子元素,position: absolute使其脱离文档流并相对于.parent进行定位,top: 50%将子元素的顶部移动到父元素高度的 50% 位置,transform: translateY(-50%)将子元素向上移动自身高度的一半,达到垂直居中效果。

  1. 行高等于容器高度(适用于单行文本)

    • 原理:对于单行文本,当行高(line - height)等于容器的高度时,文本会在容器中垂直居中。
<style>
 .parent {
      height: 100px;
      line - height: 100px;
      background - color: lightgray;
  }
</style>
<div class="parent">看我实现了垂直居中</div>
  • 解释.parent是包含文本的容器元素,height: 100px定义了容器的高度,line - height: 100px将行高设置为与容器高度相同,background - color: lightgray设置背景颜色。这样,文本在容器中就会垂直居中。

  1. 表格单元格(table - cell)布局

    • 原理:将父元素设置为display: table - cell,并结合vertical - align: middle属性,可以使子元素在垂直方向上居中。
    • 示例代码
<style>
 .parent {
      display: table - cell;
      height: 200px;
      vertical - align: middle;
      background - color: lightgray;
  }
</style>
<div class="parent">
  <div class="child">看我实现了垂直居中</div>
</div>
  • 解释.parent作为父元素,display: table - cell将其显示方式设置为类似表格单元格,height: 200px设置高度,vertical - align: middle使子元素(.child)在垂直方向上居中,background - color: lightgray用于设置背景颜色。这种方法在一些场景下也能有效地实现垂直居中。