学无先后,达者为师

网站首页 编程语言 正文

css让不定宽高的div,垂直水平居中

作者:阿坤_21 更新时间: 2022-07-21 编程语言

如何让一个div在垂直水平方向上居中对齐?

方法一:使用transform

.parent {
  background-color: #fff;
  width: 400px;
  height: 400px;
}
.son {
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: pink;
}

方法二: flex弹性布局

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 400px;
  height: 400px;
  background-color: #fff;
}
.son {
  background-color: pink;
}

方法三: 绝对定位

.parent {
  position: relative;
  width: 400px;
  height: 400px;
  background-color: #fff;
}
.son {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  background-color: pink;
}


原文链接:https://blog.csdn.net/zoukunyang/article/details/124737218

栏目分类
最近更新