/ 博客 / 221浏览

Display:Grid

文章目录

今天在美化博客时发现可以用display:grid替代display:flexdisplay:block@media等过时的办法,特记载如下。

新旧对比

display:grid是一种较新的前端神器,可以完美匹配任何前端布局,不严谨的说,相当于display:flex的升级版。它还支持前几行两端对齐最后一行靠左这样的特殊布局。唯一不完美之处在于ie11等老浏览器不兼容。

display:flex是一种稍旧的前端方法,可以匹配95%以上的前端布局,完美替代float+clear:bothdisplay:tabledisplay:block等。不完美之处在于超过一层后样式相当复杂,以及如前所说前几行两端对齐最后一行只能两端对齐。

官方说明

Grid Layout is a new layout model for CSS that has powerful abilities to control the sizing and positioning of boxes and their contents. Unlike Flexible Box Layout, which is single-axis–oriented, Grid Layout is optimized for 2-dimensional layouts: those in which alignment of content is desired in both dimensions.

CSS Grid Layout Module Level 1. https://drafts.csswg.org/css-grid. CSS Working Group Editor Drafts. 2019-11-04

示例

/* 父块 */
/* ie11不支持display:grid,改用flex */ 
.items {
     display: flex;
     display: -webkit-flex;
     justify-content: center;
     flex-wrap: wrap;
 }

/* 主流支持display:grid */
@supports (display: grid) {
     .items {
         display: grid;
         justify-content: space-around;
         grid-template-columns: repeat(auto-fill, 120px);
         grid-gap: 20px;
     }
 }

/* 子块 */
.list-item {
     display: grid;
 }

6

  1. 响石潭

    我的博客css东拼西凑的达到效果,需要简化了

    Sogou Explorer · Windows 10
  2. fooleap

    学不动了,沉迷在 flex 布局无法自拔。

    Google Chrome 78 · Windows 7
    1. S

      @fooleap哈哈哈

      Firefox 71 · Mac OS X 10.15
  3. Betty

    现在还愿意支持 IE 的估摸着就只有政府网站了吧,哈

    Google Chrome 79 · Mac OS X 10.15
    1. S

      @Betty还有银行……

      Firefox 72 · Mac OS X 10.15
      1. Betty

        @S你不说我完全忘记这茬了,感谢手机时代的 APP 拯救了普通用户

        Google Chrome 79 · Mac OS X 10.15

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注