如何使用 CSS grid 属性使 <div> 居中?
CSS grid 是 CSS 中最广泛使用的元素之一。该元素类似于弹性框。CSS 网格是 Web 上的二维布局系统。借助网格,我们可以将元素放置在行、列或两者中。
在本文中,我们将了解如何仅使用 CSS grid 属性使 div 居中。我们将使用 place-items 和 align-items 属性来实现此目的。
使用 Place-items 属性
Grid-container 类将 display 属性设置为 grid 以创建网格容器,并将 place-items 属性设置为 center 以使项目在网格中心对齐。内部 div 将在网格容器内垂直和水平居中。
语法
.grid-container {
display: grid;
place-items: center;
}
在这里,我们使用 display 属性将 HTML 容器定义为网格元素。接下来,我们使用 place-items 属性将网格居中对齐。请注意,place-items 属性仅适用于网格元素。
示例
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container{
display: grid;
place-items: center;
border:2px solid black;
width:50%;
}
body{
display: grid;
place-items: center;
}
</style>
</head>
<body>
<div class="container">
<p>This is the grid element</p>
</div>
</body>
</html>
使用 justify-items 属性
在网格布局中,我们有多个选项可以使 div 居中。另一种使 div 居中的方法是使用 justify-items 属性。
语法
<element selector>{
display: grid;
Justify-items: center{
}
在上述语法中,我们使用 display 属性将 HTML 标签定义为网格元素,并使用 justify-items 属性插入 div。
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container {
display: grid;
justify-items: center;
border: 2px solid yellow;
width:50%;
}
body {
display: grid;
place-items: center;
}
</style>
</head>
<body>
<div class="container">
<p>How to center align the grid element</p>
</div>
</body>
</html>
说明
CSS 样式将".container"类的 display 属性设置为网格,其中对齐的元素居中,并带有黄色 2px 实线边框。宽度设置为 50%,以使内容在父元素内居中。
<body> 元素将其 display 属性设置为网格,并使用 place-items 属性使内容在页面内水平和垂直居中。<div class="container"> 元素是父元素,包含居中文本"如何使网格元素居中"。
使用自对齐属性
另一种选择是使用自对齐属性。我们有 align-self 和 justify-self 属性可以使 div 居中。
语法
<parent element selector>{
display: grid;
}
<child element selector>{
align-self: center;
justify-self: center;
}
首先,我们定位到父元素。我们将父元素声明为网格元素。接下来,我们定位到子元素。我们使用 align-self 和 justify-self 属性使网格居中对齐。
示例
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container {
display: grid;
width: 50%;
border: 2px solid purple;
height: 5vh;
}
.child {
align-self: center;
justify-self: center;
}
body {
padding: 5vh;
display: grid;
place-items: center;
}
</style>
</head>
<body>
<div class="container">
<div class="child">Placing the child div to center</div>
</div>
</body>
</html>
head 部分包含页面的 CSS 样式。.container 类将 display 设置为网格,将 justify-items 设置为居中,并将宽度设置为 50%,并带有黄色边框。
body 元素将 display 设置为网格,并使用 place-items 将内容水平和垂直居中。类名为"container"的 div 元素充当父元素,并包含文本"如何使网格元素居中",该元素将水平居中。
总结
使用 CSS 网格布局,您可以通过多种方式使 div 居中。具体方法取决于您的需求和网格结构。本文将帮助您了解如何使用 CSS 夹点属性使 <div> 居中。
相关文章
有用资源
css 参考教程 - 该教程包含有关 css 的更多信息:https://www.cainiaomax.com/css/

