首页 > 解决方案 > CSS网格输入大小增加

问题描述

我有几个关于 CSS 网格的问题。

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

这是一个例子:

.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>

标签: csscss-grid

解决方案


1. 为什么label和input的大小和grid的行高匹配并填充?

因为 height 是auto,所以在 CSS Gridauto中被拉伸了。stretch由于对齐属性align-items和的默认值justify-content,我们可以覆盖它:

  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-self align-self


2、为什么label和input元素在css grid中显示为block,而在简单div中显示为inline元素?

3. 为什么浏览器会忽略将它们的显示覆盖到内联?

规范说:

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


推荐阅读