【记录】一个经典场景的布局方案

328 阅读2分钟

前言

最近刚好在写页面,遇到一个比较经典的场景,当时记录一下吧。

业务场景

一个铺满的背景(背景图,背景色,多色分割……),中间有一个内容区(图片,文案)。如:

template (1).png

template (1).png 手残p图,不要在意。

实现方案

我想,稍有经验的道友看到这种场景,多半是轻蔑一笑,心想:“简直不要太简单好吗?” 以图一为样例。

方案一

别跟我讲什么布局,直接一整张图盖上去,还背景,内容,哼!垃圾。

方案二

用背景图铺满,内容区居中。

<div class="box">
  <div class="content"></div>
</div>
.box {
  width: 100%;
  height: 100%;
  background: url("line.png") repeat-x;
  display: flex;
  justify-content: center;
  align-items: center;  
}
.content {
  width: 300px;
  height: 300px;
  background-color: blue;
}

优势:兼容性强。
劣势:需要UI提供1像素背景图;纯色时增加一次请求(请求图片)或增加css体积(base64);拓展性差,只能使用背景图和背景色。

方案三

背景跟内容区作为兄弟节点叠加在一起。

<div class="box">
  <div class="bg">
    <div class="white"></div>
    <div class="grey"></div>
  </div>
  <div class="content"></div>
</div>
.box {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center; 
}
.bg {
  position: absolute;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}
.white {
  flex: 1;
  background-color: white;
}
.grey {
  flex: 1;
  background-color: grey;
}
.content {
  position: relative;
  background-color: blue;
  width: 300px;
  height: 300px;
}

优势:兼容性强;易拓展,使用灵活(背景作为独立的块,可以随意玩耍);适用场景多。
劣势:少了一次找UI小姐姐的机会

总结

方案远不止这些,根据实际情况选择最简单,最直接的解决方案才是王道。没有什么比搞完准点下班更快乐

最后

本人文笔差,不知道有没有表述清楚内心的想法,还请谅解,如有更好的方案,还请不吝赐教。

祝大家,一夜暴富。