CSS相关知识点

71 阅读2分钟

1.1 垂直居中

1.1 垂直居中

<div class="parent">
  <div class="child">hello world</div>
<div>
  1. position + margin:auto
.parent {
  width: 400px;
  height: 300px;
  position: relative;
}

.child {
  width: 300px;
  height: 200px;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
}
  1. position + translate
.parent {
  width: 400px;
  height: 300px;
  position: relative;
}

.child {
  width: 300px;
  height: 200px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
  1. position + 负margin

此 margin 减去的宽高是相对于自身而言的。

.parent {
  width: 400px;
  height: 300px;
  position: relative;
}

.child {
  width: 300px;
  height: 200px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -100px;
  margin-left: -150px;
}
  1. table
.parent {
  width: 400px;
  height: 300px;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

.child {
  display: inline-block;
  width: 300px;
  height: 200px;
}
  1. flex
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}
  1. gird

自己实现时发现无法垂直居中(结果待定)

.parent {
  display: grid;
  justify-content: center;
  align-items: center;
}
  1. 单行文本
height: 10px;
line-height: 10px;
text-align: center;

1.2 水平居中

  1. 定宽:margin:0 auto
.parent {
  width: 300px;
  height: 300px;
  background: red;


}

.child {
  width: 200px;
  height: 100px;
  background: green;

  margin: 0 auto;
}
  1. 绝对定位 + left: 50% + margin: 负自身一半
.parent {
  width: 300px;
  height: 300px;
  background: red;

  position: relative;
}

.child {
  width: 200px;
  height: 100px;
  background: green;

  position: absolute;
  left: 50%;
  margin-left: -100px;
}
  1. text-align + inline-block

text-align 中的属性值是对于级联元素而言的,如果子元素是块级元素,那么此块级元素是无法实现上述效果的。

.parent {
  width: 300px;
  height: 300px;
  background: red;

  text-align: center;
}

.child {
  display: inline-block;
  width: 200px;
  height: 100px;
  background: green;
}

1.3 垂直居中

  1. position: absolute
.parent {
  width: 300px;
  height: 300px;
  background: red;

  position: relative;
}

.child {
  width: 200px;
  height: 100px;
  background: green;

  position: absolute;
  top: 50%;
  margin-top: -50px;
}
  1. table-cell + vertical-align
.parent {
  width: 300px;
  height: 300px;
  background: red;

  display: table-cell;
  vertical-align: middle;
}

.child {
  width: 200px;
  height: 100px;
  background: green;
}