CSS网格布局最后一项中心 [英] CSS grid layout last item center

查看:32
本文介绍了CSS网格布局最后一项中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网格布局为2列.我有 5格,我的第5格位于,我希望我的第5格居中.

I have a grid layout of 2 columns. i have 5 div , my 5th div coming on left and i want my 5th div to be centered.

我如何使用任何 grid属性实现这一目标?

How can i achieve that using any grid property?

我的输出:

这就是我想要的:

这是我的代码:

<style>
        .container{
            display: grid;
            grid-template-columns: 200px 200px;
            gap: 10px;
        }

        .box{
            padding: 20px;
            background-color: burlywood;
            border: 1px solid red;
        }
</style>

<div class="container">
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
</div>

推荐答案

您可以选择DOM中的最后一个 .box 跨两列.

You can select the last .box in your DOM to span across both columns.

.container {
  display: grid;
  grid-template-columns: 200px 200px;
  gap: 10px;
}

.box {
  padding: 20px;
  background-color: burlywood;
  border: 1px solid red;
}

.container .box:last-child {
 justify-self: center;
 width: calc(200px - 20px);
 grid-column-start: span 2;
}

<div class="container">
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
</div>

这里要看的主要代码是:

The main piece of code to look at here is this:

.container .box:last-child {
 justify-self: center;
 width: calc(200px - 20px);
 grid-column-start: span 2;
}

grid-column-start 告诉浏览器根据网格显示 .box 最左侧的位置.使用 span 2 表示 .box 将从其自然位置开始,并跨越2列.

grid-column-start tells the browser to render where the very left side of the .box start from based on your grid. Using span 2 says that the .box will start from its natural position and span 2 columns.

这篇关于CSS网格布局最后一项中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆