【前端面试题3】如何实现一个元素的水平垂直居中

以下是题目的布局代码:

html 复制代码
<div class="container">
  <div class="item" style="width: 100px; height: 100px; background: #999;">
    块状元素
  </div>
</div>
 
<div class="container">
  <div class="item">不定高宽的块状元素</div>
</div>
 
<div class="container">
  <span class="item">行内元素</span>
</div>
css 复制代码
.container {
  // 把代码写在这里
}
 
.container {
  height: 20rem;
  background: #ccc;
  margin: 1rem;
}

1.flex方法:

css 复制代码
.container {
  display: flex;
  justify-content: center;
  align-items: center;
}

2.grid方法:

css 复制代码
.container {
  display: grid;
  place-items: center;
}

css 复制代码
.container {
  display: flex;
  justify-content: center;
  align-items: center;
}

3.绝对定位方法:

css 复制代码
.container {
  position: relative;
}

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

.item {
  padding: 1rem;
  border: 1px solid #999;
}

.container {
  height: 12rem;
  background: #ccc;
  margin: 1rem;
}
相关推荐
天天向上10241 小时前
vue el-table实现拖拽排序
前端·javascript·vue.js
庞轩px2 小时前
模拟面试回答第十三问:JVM内存模型
jvm·面试·职场和发展
柳杉2 小时前
Three.js × Blender:从建模到 Web 3D 的完整工作流深度解析
前端·javascript·数据可视化
人工智能AI技术2 小时前
计算机专业面试必看!90%学生都踩过的算法面雷区
人工智能·面试
reembarkation3 小时前
vue3中使用howler播放音频列表
前端·vue.js·音视频
手握风云-3 小时前
基于 Java 的网页聊天室(三)
服务器·前端·数据库
xlp666hub3 小时前
深度剖析 Linux Input 子系统(3):从零写一个 Input 驱动,最详细手把手(附完整代码)
linux·面试
weixin199701080163 小时前
《识货商品详情页前端性能优化实战》
前端·性能优化
Forever7_3 小时前
重磅!Vue3 手势工具正式发布!免费使用!
前端·前端框架·前端工程化
用户806138166593 小时前
发布为一个 npm 包
前端·javascript