我有一个包含8个元素的CSS网格。列的最小值为100px,最大值为1fr。
问题在于较低分辨率的第一列的内容将其放置在2行中,我需要将其放置在1行中。我想使列适合其内容,即使它大于1fr。
我对网格的css代码是这样,
.grid-1{
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}
我知道我可以像这样解决第一列的固定大小
.grid-2{
grid-template-columns: 210px repeat(auto-fit, minmax(100px, 1fr));
}
但是,关键是我想在其他部分中使用此代码。
答案 0 :(得分:1)
要通过minmax()将列缩小到内容的宽度,可以将max-content用作最大大小,将0用作min-size,以便在其所在列的最宽内容上完全收缩。
repeat(auto-fit, minmax(0,max-content));
https://jsfiddle.net/ce6zgur8/
* {
box-sizing: border-box;
}
.grid-1{grid-template-columns: repeat(auto-fit, minmax(0,max-content));}
.grid-2{grid-template-columns: 210px repeat(auto-fit, minmax(0,max-content))}
body {
padding: 0 0 20px 0;
background-color: #eee;
font-family: "Roboto";
font-size: 14px;
font-weight: 300;
color: #555;
width: 100%;
height: 100%;
}
h2{
margin:30px 0 10px 0;
font-size:20px;
color: black;
}
.wrapper {
padding: 10px;
font: normal normal 14px/12px "Roboto", Calibri, Arial, sans-serif;
width:1366px;
border:1px solid red;
margin: 5em auto;
}
.grid-thing {
margin: 0 0 20px 0;
display: grid;
}
.grid-thing > div{
text-align: center;
border:1px solid green;
}
<div class="wrapper">
<h2>GRID 1</h2>
<div class="grid-thing grid-1">
<div>
<label for="">Search</label>
<input type="text" placeholder="Number, text, whatever...">
</div>
<div>
<label for="">From</label>
<input type="date">
</div>
<div>
<label for="">From</label>
<input type="date">
</div>
<div>
<button>Button 1</button>
</div>
<div>
<button>Button 2</button>
</div>
<div>
<input type="checkbox">
<label for="">Check?</label>
</div>
<div>
<button>Button 3</button>
</div>
<div>
<button>Button 14</button>
</div>
</div>
<hr>
<h2>GRID 2</h2>
<div class="grid-thing grid-2">
<div>
<label for="">Search</label>
<input type="text" placeholder="Number, text, whatever...">
</div>
<div>
<label for="">From</label>
<input type="date">
</div>
<div>
<label for="">From</label>
<input type="date">
</div>
<div>
<button>Button 1</button>
</div>
<div>
<button>Button 2</button>
</div>
<div>
<input type="checkbox">
<label for="">Check?</label>
</div>
<div>
<button>Button 3</button>
</div>
<div>
<button>Button 14</button>
</div>
</div>
</div>
提醒https://developer.mozilla.org/en-US/docs/Web/CSS/minmax
另请参见fit-content(x);
https://developer.mozilla.org/en-US/docs/Web/CSS/fit-content