css布局问题

css 布局问题

让一个块级元素垂直居中的方法

第一种方法

  • 利用弹性布局实现,在父容器中添加

    .out {
      width: 500px;
      height: 500px;
      background-color: skyblue;
      display: flex;
      align-items: center; /*垂直居中*/
      /*justify-content: center;*/ /*水平居中*/
    }
    .in {
      width: 100px;
      height: 100px;
      background-color: salmon;
    }

    第二种方法

设置父元素相对定位,子元素position: absolute;top: 50%;同时 margin-top 值为-(子元素高度的一半),

.out {
  width: 500px;
  height: 500px;
  background-color: skyblue;
  position: relative;
}
.in {
  width: 100px;
  height: 100px;
  background-color: salmon;
  position: absolute;
  top: 50%;
  margin-top: -50px;
}

第三种方法

在父容器中设置display:flex,子元素设置align-self:center

第四种方法

设置父元素为相对定位,子元素为绝对定位,同时设置子元素的 top,bottom,left,right 值为 0,最后设置margin:auto;这能实现块元素的垂直+水平居中

.out {
  width: 500px;
  height: 500px;
  background-color: skyblue;
  position: relative;
}
.in {
  width: 100px;
  height: 100px;
  background-color: salmon;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

让一个元素水平居中

一:行内元素

text-align: center;

二:采用 margin

margin: 0 auto;

三:采用 table 实现

.main {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
.box7 {
  display: inline-block;
}

四:利用父元素的 position

.content7 {
  position: relative;
}
.contentBo7 {
  position: absolute;
  left: 0;
  right: 0;
  width: 80%;
  border: 2px solid red;
  margin: 0 auto;
  text-align: center;
}

实现元素水平垂直居中

1.绝对定位,利用负边距

利用负边距实现子元素居中(相对于父元素(position:relative)),需已知子元素的 width 与 height;且把子元素的 position 设为 absolute,绝对定位;以及设置 left 和 top 为 50%;再加上负边距,margin-left 值为 width 的一半,同样的,margin-top 值为 height 的一半。

.page {
  width: 100%;
  height: 600px;
  background-color: pink;
  position: relative;
}
.content {
  background-color: paleturquoise;
  width: 200px;
  height: 200px;
  position: absolute;
  top: 50%;
  left: 50;
  margin-top: -100px;
  margin-left: -100px;
  overflow: auto;
}

2.绝对定位,margin: auto

使用绝对定位方式

.page {
  width: 100%;
  height: 600px;
  background-color: pink;
  position: relative;
}
.content {
  background-color: paleturquoise;
  width: 200px;
  height: 200px;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  overflow: auto;
}

3.Flex

Flex 布局即为弹性布局,只需将父元素设置三个属性即可。

.page {
  width: 100%;
  height: 600px;
  background-color: pink;
  display: flex;
  justify-content: center;
  align-items: center;
}

4.Transform

.page {
  width: 100%;
  height: 600px;
  background-color: pink;
  position: relative;
}
.content {
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

5.Table

模拟表格效果

.page {
  width: 100%;
  height: 600px;
  background-color: pink;
  display: table;
}
.content {
  text-align: center;
  vertical-align: middle;
  display: teble-cell;
}