使用 Grid 布局构建网站首页

by Chris House

译者:若愚老师

当我开始一个项目,并开始计划如何布局主页时,我的大脑复现出浮动和定位。有些人可能会使用 Bootstrap 或其他框架。 那是因为这是2016年,我们一直在用这些方法来做布局。 但假设我们乘坐时光机来到2018年,所有主流浏览器都支持CSS Grid 布局模块。此时我们的页面布局模式已经完全改变,CSS的功能最终强大到能轻松实现我们的设计目标,这是一个web开发人员最美好的时代。现在,让我们使用超赞的工具——Grid布局来创建一个主页。

设计

下面是我们将要实现的页面

在我们开始编码之前,我们需要进入网格的思维模式。 第一步是观察我们的设计稿,并将其划分为主要的网格组件。 以下是我为此设计做的划分:

你会发现整个页面分为7个顶级网格区域。 我之所以说“顶级”是因为我们可以在其内部继续嵌套网格,这正是我们将要对hero部分所做的事:

HTML

这是HTML的基本结构。 稍后我会显示整个完成的文件,但现在我已经省去了大部分的细节。 这里要注意的重要部分是作为 body 的直接后代的7个元素:top-barmain-headerheroblog-postsnewsside-bar 以及 main-footerbody将成为我们的网格容器(grid container),它的孩子将成为网格项(grid items)。

正如刚刚提到的,我们也将设置 hero 作为网格容器。 它有两个孩子,将作为网格项:messageaward

<body>

  <header class="top-bar">
    <!-- social links and contact info -->
  </header>

  <header class="main-header">
    <!-- logo and main navigation -->
  </header>

  <section class="hero">
    <div class="message">
      <!-- circular element -->
    </div>
    <div class="award">    
      <!-- award image and quote -->      
    </div>
  </section>

  <section class="blog-posts">
    <!-- blog posts and excerpts -->
  </section>

  <section class="news">
    <!-- news headlines and excerpts -->
  </section>

  <aside class="side-bar">
    <!-- critter of the month info -->
  </aside>

  <footer class="main-footer">
    <!-- footer menu and copyright -->
  </footer>

</body>  

CSS

Okey,我们按照这种方式讲解,教程中我们不会展示所有使用到的CSS,在文章的最后我会展示最终完整的文件。现在我们只关注吸引我们的网格部分以及任何与它直接相关的样式即可。

我们首先在body上定义主网格容器:

body{
  display: grid;
  grid-template-columns: 12% auto 400px 12%;
  grid-template-rows: auto auto 950px auto auto auto;
}

我们刚刚创建了一个4列6行的网格,第一列和最后一列将作为主内容两侧的填充。 我把第三列设置为400px,因为这是我们将要放置side-bar元素的地方,我们希望这是一个固定的宽度。 hero 元素(第三行)的固定高度为950px。

现在我们使用grid-template-areas来定义某个网格区域会跑到哪里。 这是非常有趣的部分:

body{
  display: grid;
  grid-template-columns: 12% auto 400px 12%;
  grid-template-rows: auto auto 950px auto auto auto;
  grid-template-areas: "top-bar     top-bar     top-bar     top-bar"
                       "main-header main-header main-header main-header"
                       "hero        hero        hero        hero"
                       ".           blog-posts  side-bar    ."
                       ".           news        side-bar    ."
                       "main-footer main-footer main-footer main-footer";  
}

grid-template-areas让我们能把元素放在任何想要放置的地方,并且对于元素的布局该属性给我们提供一个不错的可视化。 值得注意的是,这里使用的值(top-barmain-headerhero等)不是指那些元素的类名,而是指我们用grid-area属性给它们起的名字,下一步我们将对它们命名。

当网格区域名称重复时,该元素将跨越这些列/行。 例如,top-bar 横跨四列,side-bar横跨四行和五行。 .号代表空单元格。如果你回头看看上面的完整设计,您会看到这个定义如何与我们的网格模式相匹配。

假设我们已经应用了我们所有的样式,但还没有为网格项分配网格区域名称,到目前为止我们的页面看起来还不太好:

在将网格区域名称分配给网格项之前,网格将根据它们的源顺序自动将我们的元素放置在网格中。 显然这不是我们想要的。 为了使我们的布局按预期工作,我们需要定义我们的网格区域。所以我们继续往下走:

.top-bar{
  grid-area: top-bar;
} 
.main-header{
  grid-area: main-header;
} 
.hero{
  grid-area: hero;
}
.blog-posts{
  grid-area: blog-posts;
}
.news{
  grid-area: news;
}
.side-bar{
  grid-area: side-bar;
}
.main-footer{
  grid-area: main-footer;
}

需要注意的是这些名称可以随意设置。 为了方便,我选择了让它们与类名相匹配。

现在,我们已经为网格项分配了网格区域名称,它们将在被放置在网格中合适的位置。 这一步带来的变化很大:

除了 hero 部分中的网格项外,所有内容都完全按照需要正确放置,我们差不多要完成了。

但是在我们修复 hero 部分之前,我想解释一下一些难以理解的地方:主要内容两边的填充区域的设置。 作为提醒,我们再次把刚刚的设置搬过来,用如下方式调整列:

body{
  grid-template-columns: 12% auto 400px 12%;
}

设置为12%的两列用于填充主要内容两边的空白,但是它们仅用于第四行和第五行。 回想一下,我们告诉我们的top-barmain-headerheromain-footer元素跨越所有列,包括这两个“填充”列。 我们为什么这样做? 因为我们希望这些元素的背景色横跨越整个视窗宽度,且任何一侧都没有空白。 我们只想在 blog-post/newssidebar元素周围留出空白(第四行和第五行)。

为了让元素水平覆盖整个宽度,同时让元素里面的内容保存一定的padding,我们需要显示地在这些元素上设置padding:

.top-bar{
  padding: 4px 12%; 
}
.main-header{
  padding: 12px 12%;
}
.hero{  
  padding: 55px 12% 0 12%;
}
.main-footer{
  padding: 25px 12%;
}

我们给元素设置左右 padding 为12%,这和grid-template-areas定义中的第一列和最后一列的宽度是一样的。 现在,需要填充整个宽度的元素最终呈现的结果是,背景横跨水平宽度,但其内容在两侧都预留出12%的空白。 很赞!

好了,让我们来修复 hero 部分。 这也将是一个网格容器,因此我们把它定义为一个网格,就像刚刚做过的那样:

.hero{
  display: grid;
  grid-template-columns: auto 1fr auto;
  grid-template-rows: auto auto auto;
  grid-template-areas: ".       .  award"
                       "message .  .    "
                       ".       .  .    "; 
 }

这是一个3×3的网格,除了中间的列,其它都设置为 auto。 我们给中间一列大小设为1fr,因为我们希望在第一列和最后一列用东西填充后,剩下的空间完全需要完全填满。

hero中只有两个元素:messageaward。 我们要message占据第二行的第一列,我们要award占据第一行的第三列。所以我们的完整网格定义应该如下所示:

.hero{
  display: grid;
  grid-template-columns: auto 1fr auto;
  grid-template-rows: auto auto auto;
  grid-template-areas: ".       .  award"
                       "message .  .    "
                       ".       .  .    ";  
 }

下面我们所要做的就是命名我们的元素:

.message{
  grid-area: message;
}
.award{
  grid-area: award;
}

就这样,messageaward卡入到位,我们的页面完成:

引入响应式

CSS Grid 使用媒体查询让重新排列整个布局变得非常简单。你所做的就是重新放置你的网格项。现在回到我们的设计,简单起见,我们只对两个宽度临界值做响应式处理,1600px 和 1050px。我们需要对一些元素(padding、margin等)进行一些小的样式调整,但是我不会把所有的样式调整都全部展示在这里。后面我会放出完整的代码,现在我们只需要关注关注网格相关的东西即可。

1600px 这个临界点的处理比较简单,当浏览器宽度到底1600px时我们将减少网站外部填充的地方。 之所以选择1600px,是到了这个宽度后12%填充看起来不太合适。为了解决这个问题,我们需要做的是在body上改变grid-template-columns的值,将第一列和最后一列减少到2%。 我们还需要调整其他元素的填充以匹配:

@media (max-width: 1600px) {
  body{
    grid-template-columns: 2% auto 400px 2%;
  }
  .top-bar{
    padding: 4px 2%;
  }
  .main-header{
    padding: 12px 2%;
  }
  .hero{
    padding: 55px 2% 0 2%;
  }
  .main-footer{
    padding: 25px 2%;
  }
}

对于下一个临界值,我们对网格项重新排列,使它们排列在一个列中。 再次回头看看我们原来的代码是如何对body进行设置的:

body{
  display: grid;
  grid-template-columns: 12% auto 400px 12%;
  grid-template-rows: auto auto 950px auto auto auto;
  grid-template-areas: "top-bar     top-bar     top-bar     top-bar"
                       "main-header main-header main-header main-header"
                       "hero        hero        hero        hero"
                       ".           blog-posts  side-bar    ."
                       ".           news        side-bar    ."
                       "main-footer main-footer main-footer main-footer";  
}

下面是重新设置的媒体查询:

@media (max-width: 1050px) {
  body{
    grid-template-columns: 3% auto 3%;
    grid-template-rows: auto auto auto auto auto auto auto;
    grid-template-areas: "top-bar     top-bar     top-bar"
                         "main-header main-header main-header"
                         "hero        hero        hero"
                         ".           blog-posts  ."
                         ".           news        ."
                         ".           side-bar    ."
                         "main-footer main-footer main-footer";
  }
} 

我们在这里做了一些重要的改变:将列数从四个减少到三个,将第一列和最后一列的值改为3%(3%在较窄的宽度上优于2%),添加了 附加行,将所有行的长度改为auto,并将side-bar移动到自己的行。 现在我们的页面元素很适合在较窄的宽度下展示:

The Live Code

下面是我们的主页,以及完整的HTML和CSS文件。 你需要一个支持grid的浏览器来查看预览。 我建议启用Experimental Web Platform Features标志的Chrome 49+(地址栏输入 chrome:// flags ,并向下滚动到“Experimental Web Platform Features”)。

下面的嵌入式页面默认会以移动视图展示,可以点击“Edit on Codepen”在页面全宽下展示不同的效果:

CodePen 查看效果 Building a Home Page with Grid by Chris House (@chrishouse) .

补充:基本布局代码

179 thoughts on “使用 Grid 布局构建网站首页”

  1. Does your site have a contact page? I’m having problems locating it but, I’d like to shoot you an e-mail. I’ve got some recommendations for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it improve over time.|

  2. Greetings! I’ve been following your web site for a while now and finally got the courage to go ahead and give you a shout out from Austin Tx! Just wanted to mention keep up the great job!|

  3. Just want to say your article is as astonishing. The clearness in your post is simply excellent and i can assume you’re an expert on this subject. Well with your permission let me to grab your feed to keep up to date with forthcoming post. Thanks a million and please keep up the gratifying work.|

  4. hello there and thank you for your info – I have definitely picked up anything new from right here. I did however expertise a few technical points using this web site, since I experienced to reload the website a lot of times previous to I could get it to load correctly. I had been wondering if your web hosting is OK? Not that I’m complaining, but slow loading instances times will very frequently affect your placement in google and can damage your high-quality score if ads and marketing with Adwords. Well I’m adding this RSS to my email and can look out for a lot more of your respective exciting content. Make sure you update this again very soon.|

  5. whoah this blog is great i love studying your articles. Stay up the great work! You understand, many individuals are searching around for this information, you can help them greatly. |

  6. Greetings I am so thrilled I found your site, I really found you by accident, while I was browsing on Bing for something else, Regardless I am here now and would just like to say thanks for a incredible post and a all round entertaining blog (I also love the theme/design), I don’t have time to go through it all at the minute but I have saved it and also included your RSS feeds, so when I have time I will be back to read much more, Please do keep up the great b.|

  7. Thank you for sharing your info. I truly appreciate your efforts and I will be waiting for your further write ups thanks once again.|

  8. I blog frequently and I genuinely thank you for your content. Your article has really peaked my interest. I am going to bookmark your site and keep checking for new details about once a week. I opted in for your Feed as well.|

  9. Hola! I’ve been reading your blog for a while now and finally got the bravery to go ahead and give you a shout out from Houston Texas! Just wanted to mention keep up the excellent work!|

  10. Hello everybody, here every person is sharing such familiarity, so it’s good to read this web site, and I used to pay a visit this blog daily.|

  11. What i don’t realize is actually how you’re not really a lot more smartly-preferred than you may be right now. You are very intelligent. You already know therefore considerably in relation to this topic, produced me in my opinion believe it from so many numerous angles. Its like women and men are not interested unless it’s something to accomplish with Lady gaga! Your own stuffs outstanding. All the time handle it up!|

  12. I have been browsing online more than three hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. In my opinion, if all website owners and bloggers made good content as you did, the net will be a lot more useful than ever before.|

  13. After going over a number of the articles on your site, I honestly like your way of writing a blog. I book marked it to my bookmark webpage list and will be checking back soon. Take a look at my website too and let me know what you think.|

  14. Hello everyone, it’s my first go to see at this website, and article is in fact fruitful in support of me, keep up posting these types of articles or reviews.|

  15. Hi there would you mind letting me know which web host you’re working with? I’ve loaded your blog in 3 completely different internet browsers and I must say this blog loads a lot faster then most. Can you suggest a good web hosting provider at a reasonable price? Thanks, I appreciate it!|

  16. My programmer is trying to convince me to move to .net from PHP. I have always disliked the idea because of the costs. But he’s tryiong none the less. I’ve been using WordPress on a number of websites for about a year and am nervous about switching to another platform. I have heard excellent things about blogengine.net. Is there a way I can import all my wordpress content into it? Any help would be really appreciated!|

  17. I’ve been surfing online more than three hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. Personally, if all webmasters and bloggers made good content as you did, the internet will be much more useful than ever before.|

  18. Hi there, There’s no doubt that your site may be having internet browser compatibility issues. When I take a look at your website in Safari, it looks fine however, if opening in IE, it has some overlapping issues. I just wanted to provide you with a quick heads up! Aside from that, fantastic site!|

  19. Simply wish to say your article is as astonishing. The clarity to your post is just nice and that i can suppose you are a professional on this subject. Well together with your permission allow me to grab your RSS feed to keep up to date with impending post. Thanks 1,000,000 and please carry on the gratifying work.|

  20. Thanks for your marvelous posting! I really enjoyed reading it, you will be a great author. I will make sure to bookmark your blog and will often come back in the foreseeable future. I want to encourage that you continue your great posts, have a nice day!|

  21. Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your weblog? My blog is in the exact same area of interest as yours and my visitors would really benefit from some of the information you present here. Please let me know if this okay with you. Appreciate it!|

  22. Yesterday, while I was at work, my cousin stole my iPad and tested to see if it can survive a twenty five foot drop, just so she can be a youtube sensation. My apple ipad is now broken and she has 83 views. I know this is totally off topic but I had to share it with someone!|

  23. I just like the valuable information you supply on your articles. I’ll bookmark your weblog and check once more right here regularly. I’m somewhat certain I will be told lots of new stuff right here! Best of luck for the following!|

  24. Hey there! I’m at work surfing around your blog from my new iphone! Just wanted to say I love reading your blog and look forward to all your posts! Carry on the fantastic work!|

  25. Tremendous things here. I’m very satisfied to look your article. Thanks a lot and I am looking ahead to contact you. Will you kindly drop me a mail?|

  26. Thank you for another informative web site. Where else could I get that kind of information written in such an ideal way? I’ve a venture that I’m just now operating on, and I’ve been on the look out for such information.|

  27. My brother recommended I may like this blog. He was once entirely right. This put up actually made my day. You cann’t believe just how a lot time I had spent for this information! Thanks!|

  28. Hmm it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I too am an aspiring blog blogger but I’m still new to the whole thing. Do you have any points for beginner blog writers? I’d genuinely appreciate it.|

  29. Amazing! This blog looks exactly like my old one! It’s on a completely different topic but it has pretty much the same page layout and design. Excellent choice of colors!|

  30. Useful information. Fortunate me I discovered your website by chance, and I’m surprised why this accident didn’t came about in advance! I bookmarked it.|

  31. Its like you read my mind! You seem to know so much about this, like you wrote the book in it or something. I think that you could do with a few pics to drive the message home a little bit, but instead of that, this is wonderful blog. A great read. I will certainly be back.|

  32. Good way of describing, and nice post to take facts on the topic of my presentation topic, which i am going to deliver in school.

  33. Hey are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and create my own. Do you require any coding expertise to make your own blog? Any help would be greatly appreciated!

  34. Greetings! I’ve been following your site for some time now and finally got the bravery to go ahead and give you a shout out from New Caney Tx! Just wanted to tell you keep up the fantastic work!|

  35. Hello! I know this is somewhat off-topic but I had to ask. Does managing a well-established website such as yours require a lot of work? I’m completely new to writing a blog but I do write in my diary daily. I’d like to start a blog so I can share my experience and thoughts online. Please let me know if you have any ideas or tips for new aspiring bloggers. Thankyou!|

  36. Hi would you mind stating which blog platform you’re using? I’m looking to start my own blog soon but I’m having a tough time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something completely unique. P.S Apologies for being off-topic but I had to ask!|

  37. Hi, i read your blog from time to time and i own a similar one and i was just curious if you get a lot of spam comments? If so how do you stop it, any plugin or anything you can recommend? I get so much lately it’s driving me mad so any assistance is very much appreciated.|

  38. I don’t even know how I ended up here, but I thought this post was great. I don’t know who you are but certainly you are going to a famous blogger if you aren’t already 😉 Cheers!

  39. Hello everyone, it’s my first go to see at this website, and paragraph is really fruitful in favor of me, keep up posting such posts.

  40. Thanks for any other wonderful post. Where else could anybody get that kind of information in such an ideal means of writing? I have a presentation subsequent week, and I’m at the search for such info.|

  41. It’s going to be end of mine day, but before finish I am reading this great article to improve my knowledge.

  42. Hmm is anyone else encountering problems with the images on this blog loading? I’m trying to find out if its a problem on my end or if it’s the blog. Any suggestions would be greatly appreciated.|

  43. It is perfect time to make some plans for the future and it is time to be happy. I have read this post and if I could I wish to suggest you some interesting things or tips. Maybe you can write next articles referring to this article. I desire to read more things about it!|

  44. Hello outstanding blog! Does running a blog
    such as this require a great deal of work? I’ve no knowledge of computer programming but I was hoping to start my own blog in the near
    future. Anyways, should you have any suggestions or tips
    for new blog owners please share. I know this is off subject however I simply wanted to ask.

    Many thanks!

  45. Hello Dear, are you in fact visiting this site daily, if so after that you will definitely take fastidious experience.|

  46. I believe that is among the most vital information for me. And i’m happy reading your article. But want to remark on some normal issues, The web site taste is perfect, the articles is really great : D. Excellent task, cheers|

  47. I was curious if you ever thought of changing the layout of your website? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or 2 images. Maybe you could space it out better?|

  48. My family members every time say that I am killing my time here at web, but I know I am getting familiarity all the time by reading such good articles.|

  49. Very great post. I simply stumbled upon your blog and wanted to mention that I have really loved browsing your blog posts. In any case I’ll be subscribing in your feed and I am hoping you write once more soon!|

  50. Wow, marvelous weblog format! How long have you ever been blogging for? you made running a blog look easy. The total look of your site is great, let alone the content!

  51. Undeniably believe that which you stated. Your favorite reason appeared to be on the net the simplest factor to remember of. I say to you, I certainly get irked even as folks consider concerns that they plainly do not know about. You managed to hit the nail upon the highest as neatly as outlined out the entire thing without having side effect , folks can take a signal. Will probably be again to get more. Thank you|

  52. Magnificent goods from you, man. I’ve understand your stuff previous to and you are just extremely magnificent. I really like what you’ve acquired here, really like what you’re saying and the way in which you say it. You make it enjoyable and you still take care of to keep it wise. I can not wait to read far more from you. This is really a wonderful web site.|

  53. Greetings! Very useful advice in this particular article!
    It’s the little changes that make the most important changes.
    Thanks a lot for sharing!

  54. Hey there! I could have sworn I’ve been to this site before but after checking through some of the post I realized it’s new to me. Anyhow, I’m definitely delighted I found it and I’ll be book-marking and checking back often!|

  55. Aw, this was an incredibly nice post. Taking a few minutes and actual effort to generate a good article… but what can I say… I put things off a whole lot and don’t seem to get nearly anything done.|

  56. Today, I went to the beach with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is entirely off topic but I had to tell someone!|

  57. Good day! This post could not be written any better! Reading through this post reminds me of my previous room mate! He always kept chatting about this. I will forward this article to him. Fairly certain he will have a good read. Thank you for sharing!|

  58. Magnificent web site. Lots of helpful information here. I am sending it to some buddies ans additionally sharing in delicious. And obviously, thank you to your effort!|

  59. hey there and thank you for your information – I have definitely picked up something new from right here. I did however expertise some technical issues using this website, as I experienced to reload the website lots of times previous to I could get it to load properly. I had been wondering if your web host is OK? Not that I’m complaining, but slow loading instances times will very frequently affect your placement in google and can damage your high-quality score if advertising and marketing with Adwords. Well I’m adding this RSS to my e-mail and could look out for much more of your respective intriguing content. Make sure you update this again soon.|

  60. I like the valuable information you supply in your articles. I will bookmark your weblog and test once more here regularly. I am reasonably certain I’ll be informed many new stuff proper here! Best of luck for the following!|

  61. Good – I should certainly pronounce, impressed with your site. I had no trouble navigating through all tabs as well as related information ended up being truly easy to do to access. I recently found what I hoped for before you know it at all. Reasonably unusual. Is likely to appreciate it for those who add forums or something, web site theme . a tones way for your client to communicate. Nice task.

  62. I’m still learning from you, as I’m making my way to the top as well. I definitely liked reading all that is posted on your site.Keep the tips coming. I enjoyed it!

  63. Excellent weblog here! Additionally your site a lot up fast! What web host are you the use of? Can I am getting your associate link on your host? I wish my web site loaded up as quickly as yours lol.

  64. That is very attention-grabbing, You are an excessively skilled blogger. I’ve joined your rss feed and look forward to seeking extra of your wonderful post. Also, I’ve shared your website in my social networks!

  65. I would like to consider the ability of thanking you for your professional advice I have enjoyed visiting your site. I am looking forward to the commencement of my school research and the entire groundwork would never have been complete without dropping by your website. If I could be of any help to others, I would be happy to help by means of what I have gained from here.

  66. Thank you a bunch for sharing this with all of us you actually realize what you are speaking about! Bookmarked. Kindly additionally consult with my site =). We may have a hyperlink alternate contract between us!

  67. I’m still learning from you, while I’m trying to reach my goals. I definitely enjoy reading all that is written on your site.Keep the information coming. I loved it!

  68. I think other website proprietors should take this site as an model, very clean and great user genial style and design, as well as the content. You are an expert in this topic!

  69. Very nice post. I just stumbled upon your weblog and wanted to say that I have truly loved browsing your blog posts. After all I will be subscribing for your rss feed and I hope you write once more soon!

发表评论

电子邮件地址不会被公开。