实现页面展示左右上下错位效果

发布时间 2023-04-11 15:41:56作者: 阳光下的向日葵

前言:有个需求,页面显示类似淘宝首页那样左右上下错位展示效果,还有点时间,所以试验记录下效果。

1、分左右栏布局

<html>
<style>
  .list_left,
  .list_right {
    width: 50%;
    float: left;
  }
  .list li {
      width: 45%;
      height: 6rem;
  }
  .list_left li:nth-child(2n) {
    height: 8rem;
  }
  .list_right li:nth-child(2n+1) {
    height: 8rem;
  }
</style>
  <body>
    <div class='list'>
      <ul class='list_left'>
		<li></li>
		<li></li>
        <li></li>
	  </ul>
      <ul class='list_right'>
		<li></li>
		<li></li>
        <li></li>
	  </ul>
    </div>
  </body>
 </html>

后期渲染数据的时候,遍历循环时,按 i%2 == 0 把数据插入左边,否则把数据插入右边,即可实现左右上下错位效果。

优点:左右分开处理,直观整洁

缺点:处理数据还得判断

2、通过margin-top为负值来实现

<html>
<style>
  ul{
    width: 100%;
    overflow: hidden;
  }
  ul li{
    width: 45%;
    height: 6rem;
    background: burlywood;
    float: left;
    margin-right: 2rem;
    margin-bottom: 2rem;
  }
  /* 0 2 4 6 8*/
  ul li:nth-child(2n){
    margin-right: 0;
  }
  /* 3 7 11*/
  ul li:nth-child(4n+3){
    margin-top: -3rem;
    height: 9rem;
  }
  ul li:nth-child(4n+2){
    height: 9rem;
  }
</style>
<body>
  <ul>
		<li></li>
		<li></li>
		<li></li>
		<li></li>
		<li></li>
		<li></li>
		<li></li>
		<li></li>
		<li></li>
		<li></li>
		<li></li>
		<li></li>
	</ul>
</body>
</html>

优点:显示简洁,易渲染

缺点:暂无吧

效果展示:

img