微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

css实现垂直居中显示

CSS实现垂直居中显示是网页设计中常见的需求,这篇文章将讲解几种实现方法

/* 方法一:使用绝对定位 */
.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

/* 方法二:使用flexBox */
.parent {
  display: flex;
  align-items: center;
  /* justify-content: center; (如果需要水平居中)*/
}
.child {
  /* 不需要设置任何属性 */
}

/* 方法三:使用grid */
.parent {
  display: grid;
  justify-items: center;
  align-items: center;
}
.child {
  /* 不需要设置任何属性 */
}

css实现垂直居中显示

第一种方法需要给父元素(parent)设置相对定位,给子元素(child)设置绝对定位,并使用top和transform属性实现垂直居中。虽然实现简单,但会影响到父元素的布局。

第二种方法使用flexBox,只需要给父元素设置display:flex,align-items:center属性即可实现垂直居中。这种方法兼容性较好,但如果需要水平居中,还需要添加justify-content:center属性

第三种方法使用grid布局,需要给父元素设置display:grid、justify-items:center和align-items:center属性。同第二种方法,子元素不需要设置任何属性。不过需要注意的是,使用grid可能会和其他布局属性产生冲突。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。