我正在尝试创建自己的 CSS 网格,带有偏移类。
问题是,当我将偏移类应用于列时,它会弄乱它的宽度,并且列变得非常窄。如果没有偏移类,宽度就可以完美工作。
/* grid system */
.container {
background: #999;
margin: 0 auto;
padding: 0 15px;
max-width: 1680px;
width: 100%;
}
.row {
display: grid;
grid-template-columns: repeat(12, 1fr);
margin: 0 -15px;
}
.col {
outline: 2px white dashed;
padding: 15px;
}
/* cols */
.col-8 {
grid-column: span 8;
}
/* col offsets */
.col-offset-1 {
grid-column-start: 2;
}
<div class="container">
<main class="row">
<div class="col-8 col-offset-1">
<p>
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Illum quibusdam perspiciatis, magnam autem velit totam quae consectetur tempora qui ipsum odit sed voluptatem quaerat error quos iusto aliquid nesciunt tenetur.
</p>
</div>
</main>
</div>
我还意识到,如果我为 CSS 指定一个起始列,那么它就可以正常工作在这种情况下。但我不能将其设置为每个列类,因为它会弄乱我的布局:
/* grid system */
.container {
background: #999;
margin: 0 auto;
padding: 0 15px;
max-width: 1680px;
width: 100%;
}
.row {
display: grid;
grid-template-columns: repeat(12, 1fr);
margin: 0 -15px;
}
.col {
outline: 2px white dashed;
padding: 15px;
}
/* cols */
.col-8 {
grid-column: 1 / span 8;
}
/* col offsets */
.col-offset-1 {
grid-column-start: 2;
}
<div class="container">
<main class="row">
<div class="col-8 col-offset-1">
<p>
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Illum quibusdam perspiciatis, magnam autem velit totam quae consectetur tempora qui ipsum odit sed voluptatem quaerat error quos iusto aliquid nesciunt tenetur.
</p>
</div>
</main>
</div>
一种方法如下,它使用自定义 CSS 属性将相关偏移量传递给您要放置的
.col-8
内容:
/* grid system */
.container {
background: #999;
margin: 0 auto;
padding: 0 15px;
max-width: 1680px;
width: 100%;
}
.row {
display: grid;
grid-template-columns: repeat(12, 1fr);
margin: 0 -15px;
}
.col {
outline: 2px white dashed;
padding: 15px;
}
/* cols */
.col-8 {
/* here we're using the CSS calc() function to determine the
column-grid-line at the start of the grid-column-track into
which the content should be placed; this takes the form of
1 + <offset>, as the starting edge of the grid is number 1.
Into this calculation we pass in the --offset custom
property or, if that property isn't defined, the default of
0: */
grid-column: calc(1 + var(--offset, 0)) / span 8;
}
/* col offsets */
.col-offset-1 {
/* here we define the --offset property with the appropriate
value: */
--offset: 1;
}
<div class="container">
<main class="row">
<div class="col-8 col-offset-1">
<p>
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Illum quibusdam perspiciatis, magnam autem velit totam quae consectetur tempora qui ipsum odit sed voluptatem quaerat error quos iusto aliquid nesciunt tenetur.
</p>
</div>
</main>
</div>
参考资料: