css居中对齐

172 阅读2分钟

text-align: center

仅对文字、图片、按钮等行内元素有效(display设置为linline-*包括inlineinline-blockinline-flexinline-table等)进行水平居中

padding

通过设置padding可以实现对边距固定,高度不定的子元素的垂直居中对齐展示

.parent {
  padding: 30px;
  text-align: center;
}
.child {
  display: inline-block;
}

margin

若是只需要设置实现对块级元素的水平居中只需设置margin: auto;;若要设置水平垂直居中,代码如下:

.parent{
  height: 300px;
  position: relative;
}
.child{
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100px;
  height: 100px;
  margin: auto;
}

line-height

使用 line-height=height实现对文字的垂直居中 ,将文字高度设置为容器高度,仅对一行文字有效

display:table-cell

在表格中可以通过设置<table align="center">是单元格的内容居中显示,HTML5 不支持 <table>中使用 align 属性。请使用 CSS 代替。在 HTML 4.01 中,<table>align 属性 已废弃。`在非表格元素中使用,可以参考如下写法:

.parent{
  height: 300px;
  width: 300px;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
.child{
  display: inline;
} 

负边距

当元素宽高已知,子容器绝对定位,top:50% left:50% margin-top margin-left的值取该容器高度,宽度的一半的负值

.parent{
  position: relative;
  height: 500px;
}
.child{
  position: absolute;
  width: 200px;
  height: 300px;
  top: 50%;
  left: 50%;
  margin: -150px -100px;
}

calc

.parent{
  position: relative;
  height: 500px;
}
.child{
  position: absolute;
  width: 200px;
  height: 300px;
  left: calc(50% - 100px);
  top: calc(50% - 150px);
}

transform

当元素宽高未知

.parent{
  position: relative;
  height: 500px;
}
.child{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

box

box属性结合box-pack: center(水平),box-align: center(垂直)使用。目前主流浏览器都不支持,各浏览器通过相应的私有属性支持,如下代码:

.parent{
/* Internet Explorer 10 */
  display: -ms-flexbox;
  -ms-flex-pack: center;
  -ms-flex-align: center;

  /* Firefox */
  display: -moz-box;
  -moz-box-pack: center;
  -moz-box-align: center;

  /* Safari, Opera, and Chrome */
  display: -webkit-box;
  -webkit-box-pack: center;
  -webkit-box-align: center;
}

flex

有一个或多个元素需要居中,使用弹性布局,对子元素进行上下、左右居中对齐展示

.parent{
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction:column; //改变主轴为cross axis
}

.parent{
  display: flex;
}
.child{
  margin: auto;
}

grid

.parent{
  display: grid;
  height: 300px;
  justify-content: center;
  align-items: center;
}

.parent {
  height: 300px;
  display: grid;
}
.child {
  margin: auto;
}

.parent {
  height: 300px;
  display: grid;
  place-items: center;
}

fit-content

若子元素包含float: left;属性, 为了让子元素水平居中, 则可让父元素宽度设置为fit-content,并且配合margin。代码如下:

.parent {
  background: #ff8787;
  height: 300px;
  width: fit-content;
  margin: 0 auto;
}
.child {
  background: #e599f7;
  height: 300px;
  width: 300px;
  float: left;
}

使用伪类:before

<div class="parent">
  <div class="child">水平垂直居中</div>
</div>
.parent {
  text-align: center;
}
.parent:before {
  content: "";
  width: 0;
  height: 100%;
  display: inline-block;
  vertical-align: middle;
}
.child {
  display: inline-block;
}