如何使用JavaScript将Flexbox容器对齐到中心
在本文中,我们将使用JavaScript设置内容的对齐方式。使用 DOM Style alignContent属性 来对齐柔性容器的项目,当它们未使用交叉轴上的所有可用空间时。
语法:
对象.style.alignContent = "center"
属性值:
- center: 将文本内容放在容器的中心位置。
示例: 此示例将alignContent属性值设置为center,以将项目对齐到盒子的中心。
<!DOCTYPE html>
<html>
<head>
<title>
如何使用JavaScript将Flexbox容器对齐到中心?
</title>
</head>
<body>
<center>
<h1 style="color: green">
GeeksforGeeks
</h1>
<h3>
如何使用JavaScript将Flexbox容器对齐到中心?
</h3>
<p>
点击按钮更改alignContent为"center"
</p>
<div class="main">
<div style="background-color:green;">
Geeks
</div>
<div style="background-color:lightgreen;">
For
</div>
<div style="background-color:green;">
Geeks
</div>
</div>
<button onclick="changeAlign()">
更改alignContent
</button>
</center>
</body>
</html>
.main {
width: 250px;
height: 300px;
border: 1px solid;
display: flex;
flex-flow: row wrap;
}
.main div {
width: 250px;
height: 70px;
font-size: 2rem;
text-align: center;
}
function changeAlign() {
document.querySelector('.main')
.style.alignContent = "center";
}
输出: 点击此处查看在线输出。
阅读更多:JavaScript 教程