Hkc

vuePress-theme-reco Hkc    2025
Hkc Hkc

Choose mode

  • dark
  • auto
  • light
TimeLine
GitHub
author-avatar

Hkc

25

Article

13

Tag

TimeLine
GitHub
  • Vue

  • Websocket

  • JS

  • CSS

    • 元素水平垂直居中
    • chrome控制字体小于12px
    • css绝对定位误区
    • 多行文本超出省略显示
  • Canvas

  • HTTP

  • GIT

  • SERVER

  • MORE

元素水平垂直居中

vuePress-theme-reco Hkc    2025

元素水平垂直居中

Hkc 2018-02-25 css

html 代码:

<div class="box border">
  <div class="content"></div>
</div>

# 使用 flex 布局达到垂直居中的效果,少数旧浏览器可能不兼容。

.box {
  display: flex;
  height: 600px;
  width: 600px;
  border: 1px solid #000;
  align-items: center;
  justify-content: center;
}
.content {
  width: 300px;
  height: 300px;
  background: red;
}

# 使用相对定位和绝对定位以及 margin 值来实现元素的水平垂直居中

.box {
  height: 600px;
  width: 600px;
  border: 1px solid #cccccc;
  position: relative;
}
.content {
  position: absolute;
  width: 300px;
  height: 300px;
  background: red;
  top: 50%;
  left: 50%;
  margin-left: -150px;
  margin-top: -150px;
}

# 使用绝对和相对定位

.box {
  height: 600px;
  width: 600px;
  border: 1px solid #cccccc;
  position: relative;
}
.content {
  position: absolute;
  width: 300px;
  height: 300px;
  background: red;
  margin: auto;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

# 单行元素字体垂直居中

 {
  text-align: center;
  line-height: 外层元素高度;
}