Grid wrapper - CSS: Cascading Style Sheets 编辑

The grid wrapper pattern is useful for aligning grid content within a central wrapper, while also allowing items to break out and align to the edge of the containing element or page when desired.

Requirements

Items placed on the grid should be able to align to a horizontally-centered max-width wrapper and/or the outer edges of the grid.

Recipe

Download this example

Choices made

This recipe uses the CSS Grid minmax()() function to define the grid track sizes in the grid-template-columns property. For the central columns with a maximum width we can set a minimum value of 0 or greater and a maximum value that specifies the maximum size the column tracks will grow to. Using a numeric unit (pixels, ems, rems) will create a fixed maximum size for the central wrapper, whereas using percentage values or viewport units will mean this wrapper grows or shrinks in response to its context.

The outer two columns have a maximum size of 1fr, meaning that they will each expand to fill the remaining available space in the grid container.

Useful fallbacks or alternative methods

When using this recipe at page level it can be useful to set a max-width along with left and right auto margins to center the content horizontally:

.grid {
  max-width: 1200px;
  margin: 0 auto; // horizontally centers the container
}

/* Remove the max-width and margins if the browser supports Grid */
@supports (display: grid) {
  .grid {
    display: grid;
    /* Other grid code goes here */
    max-width: none;
    margin: 0;
  }
}

To “break out” a full-width item to the edge of the viewport you can then use this trick (courtesy of Una Kravets):

.item {
  width: 100vw;
  margin-left: 50%;
  transform: translate3d(-50%, 0, 0);
}

This gives a good approximation of the layout, only without the benefit of being able to align items easily on an exact grid.

Accessibility concerns

Although Grid enables us to position items anwhere (within reason), it is important when placing items using CSS Grid that your underlying markup follows a logical order (see CSS Grid layout and accessibility for more details).

Browser compatibility

BCD tables only load in the browser

The various layout methods have different browser support. See the charts below for details on basic support for the properties used.

The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

grid-template-columns

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:114 次

字数:4789

最后编辑:8年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文