Web前端入门第 34 问:CSS 常见布局

Web 网页中,所有元素都是盒模型构成的,一个大盒子套一个或者多个小盒子,再用更大的盒子把大盒子给圈起来,这就构成了基本的 HTML 结构,再利用 CSS 把盒子装修得好看一些,最后把它放在正确位置,就是我们所看到的网页。

布局的作用就是要把元素摆放在合适的位置,让网页看起来不显得空闹闹的,也不要显得拥挤。

要摆放元素到合适的位置不是设置某一个元素能达到效果的,而是经常需要父元素和子元素配合,才能达到目标。

元素堆叠

看这么一段的代码,没有任何控制布局情况下,元素会按照出现顺序进行堆叠显示

1
2
3
4
5
<style> .box { font-size: 20px; margin: 20px; width: 250px; height: 180px; border: 2px solid #ff4757; } .box .item { border: 2px solid rgba(0,255,0,1); width: 30px; height: 30px; } </style>

效果:

需求一

现要求元素控制在一行显示。

flex 弹性盒子

给外层盒子添加 display: flex; 即可将元素改为弹性盒子。

.box {
  display: flex;
}

效果:

grid 网格

让外层盒子变为网格,可让元素在一行中显示。

.box {
  display: grid;
  grid-template-columns: repeat(auto-fit, 30px);
}

效果:

inline-block 内联块

除了 flex,还可以控制子元素显示为内联块 inline-block,让元素在一行中显示。

.box .item {
  display: inline-block;
}

效果:

注意:inline-block 让元素变为了内联块,会像文字、图片一样排版,所以元素之间会存在空隙,其空隙其实是元素之间的换行符造成的,可设置 font-size 为 0,让元素之间没有空隙。

float 元素浮动

还可以给元素添加浮动,让元素在一行中显示。

.box .item {
  float: left;
}

效果:

需求二

现要求元素在盒子中居中显示。

flex 弹性盒子

.box {
  display: flex;
  justify-content: center;
}

grid 网格

.box {
  display: grid;
  grid-template-columns: repeat(auto-fit, 30px);
  justify-content: center;
}

inline-block 内联块

.box {
  text-align: center;
}
.box .item {
  display: inline-block;
}

效果

为什么没有 float ?float 没办法做到元素居中显示,嗯...也不是做不到,只是需要通过计算获得元素 marginpadding,用边距做出出居中效果。

需求三

元素两端对齐显示。

flex 弹性盒子

.box {
  display: flex;
  justify-content: space-between;
}

grid 网格

.box {
  display: grid;
  grid-template-columns: repeat(auto-fit, 30px);
  justify-content: space-between;
}

效果

可以明显看到,随着需求越来越复杂,能用的方法就越少了。

其实 floatinline-block 也不是做不到这种效果,还是像上面说的一样,必须要通过计算获得边距,才能做出我们想要的样子。

需求四

元素等宽间距显示。

flex 弹性盒子

.box {
  display: flex;
  justify-content: space-around;
}

grid 网格

.box {
  display: grid;
  grid-template-columns: repeat(auto-fit, 30px);
  justify-content: space-around;
}

效果

需求五

如果元素大小不统一,默认显示效果是这样:

怎么让元素垂直居中显示?

flex 弹性盒子

.box {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

grid 网格

.box {
  display: grid;
  grid-template-columns: repeat(auto-fit, 30px);
  justify-content: space-around;
  align-items: center;
}

效果

需求六

第二个元素定位在盒子右上角。

这时候 flexgrid 都不能实现,只能通过 position 来实现了。

position 元素定位

position 属性对应的值有:

  • static 默认值,元素在正常文档流中显示。
  • relative 相对定位,元素在正常文档流中显示,但可以通过 toprightbottomleft 属性来定位。
  • absolute 绝对定位,元素脱离正常文档流,且不再占用文档流空间,可以通过 toprightbottomleft 属性来设置位置,其位置相对于最近的非 static 祖先元素,如果找不到,则相对于浏览器窗口。
  • sticky 粘性定位,如果元素正常显示,则跟 static 一样,如果元素跑到视口之外,则跟 absolute 一样,但其位置相对 可滚动 的祖先元素。
  • fixed 固定定位,元素脱离正常文档流,切不再占用文档流空间,可以通过 toprightbottomleft 属性来设置位置,其位置相对于浏览器窗口。

实现需求:

.box {
  position: relative;
}
.box .item:nth-child(2) {
  position: absolute;
  right: 0;
  top: 0;
}

效果

总结

本文仅介绍了常见的布局场景,开发中的需求千奇百怪,本文介绍的方法可能无法满足需求,这时候就需要发挥想象,在这些基础的布局方法上进行组合了。

From:https://www.cnblogs.com/linx/p/18826165
前端路引
100+评论
captcha