如果你想让容器居中,那么你可以使用css表格来创建3列.我们使两个侧柱1fr
的宽度相等,那么中间的柱就是fit-content
.然后我们可以使用align-self
将侧杆推到容器的边缘.CSS tricks在网格上有一个很好的入门读物,凯文·鲍威尔在youtube上有一个有用的视频
示例如下:
body {
font-family: "Comic Sans MS", "Comic Sans", cursive;
}
/* we've enclosed the two divs in to wrapper so we can use CSS grid */
.wrapper {
display: grid;
grid-template-columns: 1fr fit-content(0) 1fr;
align-items: start; /* place items to the top of the container */
}
#container {
aspect-ratio: 1/1;
background-color: deepskyblue;
width: 150px;
margin-right: auto;
padding: 100px;
}
#sidebar {
justify-self: end; /* push the sidebar to the right so it butts up next to the container */
background-color: #ed1c24;
width: 75px;
padding: 10px;
}
/* just some prettification */
.wrapper > div {
border: 2px solid black;
display: grid;
place-items: center;
}
<div class="wrapper">
<div id="sidebar">
<p>Sidebar</p>
</div>
<div id="container">
<p>Container</p>
</div>
</div>