grid 网格中的内容上下居中_在CSS中将元素居中的3种方法

7896c46aecd33e867d32d11eb1294794.png

Web开发人员在日常生活中遇到许多需要将元素居中的实例。面试中问的也是非常普遍和重要的概念。因此,今天我想列出我最喜欢的三种使用CSS进行事物居中的方法。

07d84f150940a19a6b7aa2718f990467.png

我们有两个div元素,一个在另一个内部。外层div具有id ='container',内部容器具有id ='content'。在其中,我们有一个图标。

<div id="container">        
  <div id="content">   
     <i class="fa fa-beer" style="font-size:24px"></i>       
  </div>      
</div>

4e192581d1e8ba7db41a16e2841eb887.png

1。使用Flexbox

我们可以使用flexbox将元素居中。为此,我们将显示属性分配给flex。对于居中项,我们使用属性justify-content和align-items并将其分配给center。

#container {
  background: #eee;
  height: 500px;
  width: 100%;

  display: flex;
  justify-content: center;
  align-items: center;
}

#content {
  background: pink;
  height: 100px;
  width: 200px;

  display: flex;
  justify-content: center;
  align-items: center;
}

2. 使用 Grid

使用网格将元素居中是一种更有效的方法。我们可以使用显示属性来利用网格。place-items属性用于使元素居中。

#container {
  background: #eee;
  height: 500px;
  width: 100%;
  position: relative;

  display: grid;
  place-items: center;
}

#content {
  top: 50%;
  background: pink;
  height: 100px;
  width: 200px;

  display: grid;
  place-items: center;
}

3.使用位置属性

另一种方法是使用位置属性使事物居中的老式方法。我们使用margin,top,right,bottom和left属性作为位置。

#container {
  background: #eee;
  height: 500px;
  width: 100%;

  position: relative;
}

#content {
  top: 50%;
  background: pink;
  height: 100px;
  width: 200px;

  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  top: 0;
  margin: auto;
  /* to align the icon */
  text-align: center;
  line-height: 120px;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值