How to center content and make the background cover the full column when using CSS Grid?(如何在使用css网格时居中显示内容,并使背景覆盖整栏?)
问题描述
当我添加此代码时:
place-items: center;
我的元素居中,但只有文本应用了背景色。
当我删除此代码时:
place-items: center;
背景色覆盖整列,但文本不再居中。
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">main {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: 100px;
grid-gap: 20px;
place-items: center;
}
p {
background-color: #eee;
}
<body>
<main>
<p>box1</p>
<p>box2</p>
<p>box3</p>
<p>box4</p>
</main>
</body>
为什么会发生这种情况?如何将内容居中并将背景颜色应用于整个栏?
推荐答案
如果没有place-items: center;,您的网格项目将被拉伸以覆盖所有区域(大多数情况下的默认行为),这就是为什么背景将覆盖很大的区域:
使用place-items: center;时,您的网格项目将适合其内容,并且它们将放置在中心;因此,背景将仅覆盖文本。
为避免这种情况,您可以将内容放在p(您的网格项目)中,而不是将p居中。不要忘了删除默认页边距以覆盖更大的区域:
main {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: 100px;
place-items: stretch; /* this is the default value in most of the cases so it can be omitted */
grid-gap: 20px;
}
p {
background-color: #eee;
/* center the content (you can also use flexbox or any common solution of centering) */
display: grid; /* OR inline-grid */
place-items: center;
/**/
margin: 0;
}
<main>
<p>box1</p>
<p>box2</p>
<p>box3</p>
<p>box4</p>
</main>
这篇关于如何在使用css网格时居中显示内容,并使背景覆盖整栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在使用css网格时居中显示内容,并使背景覆盖整栏?
基础教程推荐
- CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符 2022-01-01
- HTML5 画布调整为父级 2022-01-01
- 逻辑运算符 ||在 javascript 中,0 代表 Boolean false? 2022-01-01
- 使用 jQuery 在悬停时交换 DIV 类 2022-01-01
- 即使每次插入第一个输入的值不同,第二个输入仍显示相同的输入值 2022-01-01
- 在 Javascript 中使用 Fetch API 上传文件并显示进度 2022-01-01
- 当木偶师打开Chrome时,不能使用Chrome扩展 2022-01-01
- 最佳动态 JavaScript/JQuery 网格 2022-01-01
- 带角度的选项卡:仅使用 $http 在单击时加载选项卡 2022-01-01
- 从快速中间件中排除路由 2022-01-01
