作为前端,我们应该写过很多类似于下图所示的布局
纯css算法布局技术
-
看到这种布局我们最先想到的应该就是flex布局了,然后使用
justify-content: space-between就搞定了 但是,我们如果想要做响应式就需要给父级加
flex-wrap: wrap -
然后就会出现下面这种情况:
纯css算法布局技术
这样看起来美观不美观就不用说了吧。。。如果我们想在他换行的时候让他居中显示呢?不用js,不用媒体查询能实现吗?也是可以的,将块元素居中的最简单方法可能是将margin-left和margin-right设置为auto,然后就是下面这种效果:
纯css算法布局技术
但是!!!!!我们回到pc端的情况 是这样的:
纯css算法布局技术
虽然用margin:auto可以解决在换行情况下居中的问题,但是当回到原来的样式两边是不会对齐的。
再来看下我们想要达到的效果:
话不多说 直接上代码
// 纯css算法布局技术<header><div class="logo">前端指西</div><div class="devils-albatross">前端指北</div><div class="nav">前端指东</div></header><section class="main"><div class="inner">就是不指南</div></section>
header { width: 100%; display: flex; justify-content: space-between; padding: 0 50px; box-sizing: border-box; flex-wrap: wrap; } .header > * { flex-grow: 1; } .devils-albatross { flex-grow: 666; flex-basis: calc((650px - 100%) * 666); display: flex; justify-content: center; align-items: center; } .logo { width: 100px; height: 50px; background: red; color: white; display: flex; justify-content: center; align-items: center; font-size: 25px; margin: auto; font-weight: bold; } .nav { width: 200px; height: 50px; margin: auto; background: blue; color: white; display: flex; justify-content: center; align-items: center; flex-wrap: wrap; font-size: 25px; font-weight: bold; } section { width: 100%; height: 100px; padding: 0 50px; box-sizing: border-box; } .inner { width: 100%; height: 100%; background: gray; color: white; font-size: 25px; display: flex; justify-content: center; align-items: center; }
代码详解
首先我们给所有的子元素设置
flex-grow:1
,然后给中间的元素设为666,然后通过计算calc((650px - 100%) * 666),来达到 font-basis是否生效,当flex-basis的值使用负值时,将其视为0
-
如果感觉此文对你有所帮助,赶快点个关注吧,后续还会有更多干货输出