水平居中布局

208 阅读1分钟

垂直居中布局请移步:垂直居中布局

一、width 已知

结构:

<div id="parent">
  <div id="child"></div>
</div>

样式:

#parent {
  width: 400px;
  height: 300px;
  background-color: lightskyblue;
}

#child {
  width: 80px;
  height: 60px;
  background-color: lightpink;
}

1、position: absolute + margin-left

  • 传统方案
  • 推荐指数:☆☆☆☆☆
#parent {
  position: relative;
}

#child {
  position: absolute;
  left: 50%;
  margin-left: -40px;
}

2、position: absolute + calc()

  • Can I use ?
  • 推荐指数:☆☆☆☆(兼容性较差)
#parent {
  position: relative;
}

#child {
  position: absolute;
  left: calc(50% - 40px);
}

3、margin: 0 auto

  • 块级元素
  • 推荐指数:☆☆☆☆(适用场景有局限性)
#child {
  margin: 0 auto;
}

二、width 未知

结构:

<div id="parent">
  <div id="child">hello world</div>
</div>

样式:

#parent {
  width: 400px;
  height: 300px;
  background-color: lightskyblue;
}

#child {
  height: 60px;
  background-color: lightpink;
}

1、display: flex + justify-content: center

  • 移动端主流方案
  • Can I use ?
  • 推荐指数:☆☆☆☆☆
#parent {
  display: flex;
  justify-content: center;
}

2、display: grid + justify-content: center

  • Can I use ?
  • 推荐指数:☆☆☆(大材小用;兼容性较差)
#parent {
  display: grid;
  justify-content: center;
}

3、position: absolute + transform: translateX()

  • Can I use ?
  • 推荐指数:☆☆☆☆(兼容性较差)
#parent {
  position: relative;
}

#child {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

4、display: table + margin: 0 auto

  • 类似于 <table align="center">
  • Can I use ?
  • 推荐指数:☆☆☆(邪门歪道)
#child {
  display: table;
  margin: 0 auto;
}

5、text-align: center + display: inline-block

  • Can I use ?
  • 推荐指数:☆☆☆☆(兼容性稍微差一点点)
#parent {
  text-align: center;
}

#child {
  display: inline-block;
}