首页 > 解决方案 > 即使有背景颜色,如何制作我的 CSS 网格?

问题描述

我一直在尝试制作一个均匀的 3x2 网格。有些块更长,而其他的,我希望它们都具有相同的长度。实现这一目标的最佳 CSS 实践是什么?这些照片是我到目前为止所完成的。

在此处输入图像描述

在此处输入图像描述

HTML

<div class="column col-lg-4 col-md-6 col-sm-6 col-xs-12">
<div class="service-block-two single-item" id="service_pest">
<div class="inner-box">
<div class="content">
<div class="clearfix top-area">
<div class="text">
<h4>Insect Control</h4>
</div>
</div>
<p>Insect control is an on going maintenance issue on Nantucket. We recommend foundation treatments 2-3 times per year to keep all kinds of insects at bay. Ants, pill bugs, earwigs and a whole host of other insects can be a nuisance, let us deal with them so you don't have too.
</p><br>
<div class="link"><a href="http://mjstokes.com/buzzoff/pest-control/" class="btn-style-one">More Details</a></div>
</div>
</div>
</div>
</div>

CSS

.service-block-two{
    position:relative;
    margin-bottom: 100px;
    background-color: #f7f7f7f7;
    padding-top: 35px;
    padding-bottom: 35px;

}

.service-block-two .content p {
    text-align: center;
    width: auto;
}

.service-block-two .content .link {
    text-align: center;
}

标签: htmlcssgridpadding

解决方案


您可以使用新的CSS 网格功能轻松实现此目的。浏览器支持相当不错。您可能需要添加供应商前缀以获得最大的浏览器支持。

基本上,您需要一个父 div 来保存/包装其子级(对于您的情况,这将是灰色框)。

假设这是 HTML:

<div class="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
</div>

和使它成为 3(column)x2(row) 网格的 css 将是:

.parent {
    display: grid;
    grid-template-columns: repeat(3,1fr);
    grid-template-rows: repeat(2,1fr);
    grid-gap: 15px;
}

.child {
    background: #f7f7f7;
    padding: 15px;
}

一行中的所有列将具有相同的高度并等于最高的列。这是一个有效的codepen链接,可以查看它的实际效果。


推荐阅读