常见的css布局方式

2023-01-29  本文已影响0人  欢西西西

1. 垂直水平居中

.parent {
    display: grid;
    align-items: center;
    justify-items: center;
    /* 可以合并为:place-items: center; */
}
.parent {
    display: flex;
    align-items: center;
    justify-content: center;
}
 
.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;

  width: 200px;
  height: 100px;
}
.parent {
  position: relative;
}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  width: 200px;
  height: 100px;
}

2. 两栏布局

实现:左栏固定(宽度200px,不超过25%),右栏自适应
grid 和 flex对上下分栏和左右分栏都适用

.parent {
  display: grid;
  grid-template-columns: minmax(200px, 25%) 1fr;
}

如果要实现上下位置固定,中间高度自适应的三明治布局,也可以使用grid布局

.parent {
  height: 100vh;
  grid-template-rows: auto 1fr auto;
}
.parent {
  display: flex;
}
.child-left {
  width: max(200px, 25%);
}
.child-right {
  flex: 1;
}

flex如果需要自动换行,并且换行之后希望固定宽度的子元素能撑满整个宽度:
则父元素设置flex-wrap: wrap,原固定宽度的元素:flex: 1 1 1000px

flex: <flex-grow> <flex-shrink> <flex-basis>; // flex是这3个属性的简写

flex-grow 有多余宽度是否可扩大
flex-shrink  宽度不够是否可缩小
flex-basis 初始宽度

3. 圣杯

image.png

先将父元素分为9格

.parent {
   grid-template-rows: auto 1fr auto;
   grid-template-columns: auto 1fr auto;
   /* 可以合并写成:grid-template: auto 1fr auto / auto 1fr auto */
}

再设置每个单元格的位置

.header,
.footer {
  grid-column: 1 / 4;
 /* 是 grid-column-start: 1;  grid-column-end: 4; 的简写 */
}
.left-bar { grid-column: 1 / 2; }
.main { grid-column: 2 / 3; }
.right-bar { grid-column: 3 / 4; }

优点是:这几个元素在html里是同级元素,不需要通过嵌套再在内部布局

4. 文本垂直居中

.element {
  display: table-cell;  
  vertical-align: middle;
}

5. flex实现自适应的九宫格,每个block都为正方形

image.png
.table {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
}

.cell {
    width: 30%;
    padding-top: 30%; /* 这一步设置高度,保证盒子为正方形 */
    margin-top: 3%;
}
上一篇 下一篇

猜你喜欢

热点阅读