前端学习5 水平垂直居中

在前端中我们主要使用以下方法来实现水平垂直居中

1.单行文本

line-height + text-align

.box {
  width: 400px;
  height: 200px; 
  line-height: 200px; /* 控制行高(行间距) */
  text-align: center; /* 控制文本水平对齐方式 */
}

2.多行文本或盒子

2.1 flex 弹性布局

.container {
  display: flex;           /* 启用 Flex 布局 */
  justify-content: center; /* 主轴(默认横向)居中 */
  align-items: center;     /* 交叉轴(默认纵向)居中 */
  height: 100vh;          /* 必须设置容器高度 */
}

所有居中方法都需要明确容器尺寸,如不设置容器高度,我们将无法计算居中位置,如果是全屏居中,推荐使用height:100vh(100vh是一个相对单位,表示视口高度的100%)。

2.2 定位 + transform

父级设置为相对定位(position: relative),子级绝对定位(position: absolute)

.container {
  position: relative;  /* 定位基准 */
  height: 100vh;
}

.content {
  position: absolute;
  top: 50%;          /* 向下移动50% */
  left: 50%;         /* 向右移动50% */
  transform: translate(-50%, -50%); /* 回退自身尺寸50% */
}

2.3 定位 + margin:auto

父级设置为相对定位(position: relative),子级绝对定位(position: absolute)

.container {
  position: relative;  /* 定位基准 */
  width: 500px;
  height: 300px;
}

.content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;  /* 关键属性,自动计算剩余空间均分 */
  
  width: 200px;  /* 必须指定尺寸,否则元素会填满父容器 */
  height: 100px;
}

2.4 grid布局

.container {
  display: grid;
  place-items: center;  /* 双向居中 */
  height: 100vh;
}

display: grid 创建网格容器

place-items 是以下属性的简写:

align-items: center(垂直方向)

justify-items: center(水平方向)

2.5 表格布局

.container {
  display: table;
  width: 100%;
  height: 100vh;
}

.inner {
  display: table-cell;
  text-align: center;     /* 水平居中 */
  vertical-align: middle; /* 垂直居中 */
}

.content {
  display: inline-block; /* 必须设置为行内块 */
}

display: table 模拟表格布局

table-cell 模拟单元格

结合表格单元格的对齐特性

#前端css#
全部评论
太强了,面试几乎必问
点赞 回复 分享
发布于 05-11 04:27 湖北

相关推荐

Vue 项目的性能优化是确保应用快速、响应顺畅以及用户体验良好的关键环节。以下是一些常见的优化措施和技术,可以帮助你提高 Vue 应用的性能:https://www.nowcoder.com/issue/tutorial?zhuanlanId=j572L2&uuid=c70ee26a320a43a99f9638934d1015e61. 使用路由懒加载通过 Vue Router 设置路由懒加载,按需加载页面组件,从而减少初始加载时间。const router = new VueRouter({  routes: [    {      path: '/home',      component: () => import('./components/Home.vue'), // 懒加载    },    {      path: '/about',      component: () => import('./components/About.vue'),    },  ],});2. 组件懒加载对于较大的单页面应用,可以对一些不常用的组件进行懒加载。export default {  components: {    LazyComponent: () => import('./components/LazyComponent.vue'),  },};3. 使用计算属性代替方法当你需要对数据进行重复计算时,尽量使用计算属性,这样可以缓存结果,避免不必要的重新计算。computed: {  filteredList() {    return this.items.filter(item => item.isActive);  }}
点赞 评论 收藏
分享
评论
4
4
分享

创作者周榜

更多
牛客网
牛客企业服务