为什么 CSS 网格布局中的输入大小会增加?



我在CSS网格的上下文中有几个关于<input>元素的问题。

  1. 为什么标签和输入的大小与网格的行高匹配并填充它?
  2. 为什么标签和输入元素在 CSS 网格中显示为block,而在简单的div 中显示为内联元素?
  3. 为什么我试图覆盖它们的显示被浏览器inline忽略?

最后,这里有一个隐含的"我该如何解决这个问题"的问题。

下面是一个示例:

.wrapper {
background-color: purple;
display: grid;
grid-template-columns: 1fr 4rem 4rem 1fr;
}
.wrapper > label {
display: inline;
grid-column: 2;
background-color:green;
}
.wrapper > input[type=checkbox] {
grid-column: 3;
border: 1px solid red;
background-color: gray;
}
.wrapper > input[type=text] {
grid-column: 4;
outline: 2px solid yellow;
}
.simple {
width: 50px;
height: 100px;
background-color: blue;
}
.simple > label {
height: 50px;
}

.wrapper2 {
background-color: gray;
display: grid;
grid-template-rows: 100px;
grid-auto-rows: 100px;
grid-template-columns: 1fr 8rem 8rem 1fr;
}
.wrapper2 > label {
grid-column: 2;
display: inline;
background-color:green;
}
.wrapper2 > input[type=checkbox] {
grid-column: 3;
background-color:yellow;
border: 1px solid gray;
}
.wrapper2 > input[type=text] {
grid-column: 4;
outline: 2px solid yellow;
border: 1px solid gray;
}
<div class="wrapper">
<label for="cb">Long Label</label>
<input id="cb" type="checkbox">
<input id="t3" type="text">
</div>
<div class="simple">
<label for="cb2">Long Label</label>
<input id="cb2" type="checkbox">
<input id="t2" type="text">
</div>

<div class="wrapper2">
<label for="cb3">Long Label</label>
<input id="cb3" type="checkbox"> 
<input id="t3" type="text"> 
</div>

1. 为什么标签和输入的大小与网格的行高相匹配并填充它?

因为高度是auto的,所以在CSS网格中auto被拉伸。 因为对齐属性align-itemsjustify-content的默认值stretch,我们可以覆盖它:

  1. 块轴align-items:flex-start(垂直(
  2. 在内联轴上justify-content:flex-start(水平(

[grid] {
background: orange;
display: inline-grid;
grid-template-columns: 50px;
grid-template-rows: 50px;
}
[grid]>div {
background: red;
height: auto;
}
[fix] {
align-items: flex-start;
justify-items: flex-start;
}
[grid]>[notAuto] {
height: 30px;
width: 30px;
}
<h4>align-items: stretch; justify-items: stretch; (default)</h4>
<div grid>
<div>Text</div>
</div>
<h4>align-items: flex-start; justify-items: flex-start;</h4>
<div grid fix>
<div>Text</div>
</div>

<h4>When width/height are specified (not auto)</h4>
<div grid>
<div notAuto>Text</div>
</div>

注意:我们可以使用 Grid 项而不是容器上的-self对应项justify-selfalign-self覆盖特定元素上的该行为

<小时 />

2.为什么标签和输入元素在 css 网格中显示为块,而在简单的div 中显示为内联元素?

3. 为什么浏览器会忽略将其显示覆盖为内联?

规范说:

网格项的display值为blockified:如果生成网格容器的元素的流子元素的指定显示是内联级值,则计算到其块级等效值。

最新更新