CSS 中的居中对齐~~~

115 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

CSS的世界真是奇妙!入职该公司以来,涉及蛮多有关CSS相关的需求和内容,如animation伪类媒体查询mask布局对齐方式等等...笔者今天来记录一下和对齐方式相关的知识点,方便复习和巩固😎 工作中最常用的对齐方式莫过于居中对齐水平居中垂直居中这三种,我们一一来介绍都有哪些方法可以实现这些对齐方式。先贴出本篇文章用到的htmlcss代码

<div class="parent">
  <div class="child">Demo</div>
</div>
.parent {
  width: 100%;
  height: 100px;
  border: 1px solid black;
}

.child {
  width: 100px;
  height: 30px;
  background: #409eff;
}

垂直居中

垂直居中的效果如上。实现方式有(直接上代码):

table-cell + vertical-align

该方法用得还是比较少的。通过display: table-cell;强制父元素为表格单元格,从而进行垂直或水平居中

.parent {
  display: table-cell;
  vertical-align: middle;
}

absolute + transform

使用绝对定位并减元素自身宽高的一半来进行垂直或水平居中。适用于元素本身宽高未知的情况

.parent {
  position: relative;
}

.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

flex + align-items

较为流行的对齐方式。适用于一个或多个元素需要对齐的情况

.parent {
  display: flex;
  align-items: center;
}

水平居中

水平居中的效果如上。实现方式有(直接上代码):

inline-block + text-align

适用于文本内容inline-*类型的元素

.child {
  display: inline-block;
}

.parent {
  text-align: center;
}

table + margin

.child {
  display: table;
  margin: 0 auto;
}

absolute + transform

.parent {
  position: relative;
}

.child {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

flex + justify-content

.parent {
  display: flex;
  justify-content: center;
}

水平垂直居中

水平垂直居中的效果如上,实现方式很简单,同时满足垂直居中水平居中即可达到水平垂直居中的效果。实现方式有(直接上代码):

inline-block + table-cell

.parent {
  text-align: center;
  display: table-cell;
  vertical-align: middle;
}

.child {
  display: inline-block;
}

absolute + transform

.parent {
  position: relative;
}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

flex

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

以上就是笔者常用的有关居中对齐方式的实现方法,基本也是够用了。笔者并没有具体介绍上述实现方法中的属性,相信读者应该不会陌生这些知识点😏 如果想要深入了解flex相关属性,可以翻看笔者之前写的有关Flex 布局相关文章,感谢阅读!