css设置元素居中的方法

1、水平居中

1) text-align:设置块级元素(父级元素)里面的内容水平居中

<div class="parent">
  <span>hao </span>
</div>

.parent{
  text-align: center;
  width: 0.5rem;
  background: gray;
  color: yellow;
}

 2) width: fit-content————父级元素的宽度设为该值,由子元素内容撑开父元素的宽度,在结合margin-auto

<div class="parent">
  <span>hao </span>
</div>


.parent{
  width: fit-content;
  margin: auto;
  background: gray;
  color: yellow;
}

3)块级元素里面嵌套块级元素:margin: 0 auto

<div class="parent">
  <div class="child">hao </div>
</div>


.parent{
  background: gray;
  height: 300px;
}

.child{
  margin: 0 auto;
  background-color: red;
  width: 200px;
  height: 200px;
}

2、垂直居中

1)line-height(行内元素或者块级行内元素)—给父元素(块级元素)设置height=line-height(给块级元素设置line-height,也是作用于块级框内的内容或者行内元素、块级行内元素),父元素里面包裹行内元素,用200px - 1 em得到的值分成两份,分别加到字体的上下部分区域,这样字体就平分上下区域,形成一种垂直居中的效果

 <div class="parent">
  <span>hao </span>
 </div>


.parent{
  line-height: 200px;
  background: gray;
  color: #ffff00;
}

3、水平,垂直居中

1)定位(父元素相对定位,子元素绝对定位) + margin-top、margin-left (子元素已经知道宽高)

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


.parent{
  position: relative;
  background: gray;
  height: 300px;
}

.child{
  background-color: red;

  width: 100px;

  height: 100px;

  position: absolute;

  top: 50%;

  left: 50%;

  margin-top: -50px;

  margin-left: -50px;

}

2)定位 + margin:auto,缺点需要知道元素的宽高

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


.parent{
  position: relative;
  background: gray;
  height: 300px;
}
.child{
  height: 200px;
  width: 200px;
  background-color: red;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  margin: auto;
}

3)定位 + calc(),前提已经知道子元素的宽高

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


.parent{
  position: relative;
  background: gray;
  height: 300px;
}
.child{
  background-color: red;
  width: 100px;
  height: 100px;
  position: absolute;
  top: calc(50% - 50px);
  left: calc(50% - 50px);
}

 4) 定位 + transform,优点:不需要知道父元素的宽高

<div class="parent">
  <div class="child">fdfd</div>
</div>

.parent{
  position: relative;
  background: gray;
  height: 300px;
}
.child{
  background-color: red;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

5)padding: 固定值(父元素),父元素和子元素都为块级元素,并且不设定width

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


.parent{
  position: relative;
  background: gray;
  padding: 20px;
}
.child{
  height: 200px;
  background-color: red;
}

6)flex布局

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


.parent{
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: gray;
}
.child{
  height: 200px;
  width: 200px;
  background-color: red;
}

猜你喜欢

转载自blog.csdn.net/tangxiujiang/article/details/109955222