过去,我看到下一个 css,我在想两者之间是否存在一些实际差异
min-width: 90px;
max-width: 90px;
和
width: 90px;
最佳答案
使用 width
将简单地在元素上指定固定宽度而无需注意其内容(因此您可能会溢出):
div {
width: 80px;
border:2px solid red;
}
<div>
<img src="https://lorempixel.com/200/100/" />
</div>
使用 max-width
意味着元素的宽度将有一个上限。所以它的宽度可以从 0 到 max-width 取决于它的内容。
div {
max-width: 300px;
border: 2px solid red;
}
.diff {
display: inline-block;
}
<div>
<!-- this i a block element so max-width prevent it from taking 100% width -->
<img src="https://lorempixel.com/200/100/" />
</div>
<div class="diff">
<!-- this i an inline-block element so max-width has no effect in this case cause the content is taking less than 300px -->
<img src="https://lorempixel.com/200/100/" />
</div>
<div>
<!-- You have overflow because the element cannot have more than 300 of width -->
<img src="https://lorempixel.com/400/100/" />
</div>
min-width
指定宽度的下限。因此元素的宽度将从 min-width 到 ...(这将取决于其他样式)。
div {
min-width: 300px;
border: 2px solid red;
}
.diff {
display: inline-block;
min-height:50px;
}
<div>
<img src="https://lorempixel.com/200/100/" />
</div>
<div class="diff">
</div>
<div class="diff">
<img src="https://lorempixel.com/200/100/" />
</div>
<div>
<img src="https://lorempixel.com/400/100/" />
</div>
因此,如果您指定 min-width
和 max-width
,您将设置一个下限和上限,如果两者相等,则与简单的一样指定一个宽度
。
div {
min-width: 300px;
max-width: 300px;
border: 2px solid red;
}
.diff {
display: inline-block;
min-height:50px;
}
<div>
<img src="https://lorempixel.com/200/100/" />
</div>
<div class="diff">
</div>
<div class="diff">
<img src="https://lorempixel.com/200/100/" />
</div>
<div>
<img src="https://lorempixel.com/400/100/" />
</div>
特殊情况
在某些特殊情况下,width
不会给出与 min-width
/max-width
相同的结果,就像我们有的 Flexbox允许元素的收缩特性to shrink to fit its container
.box {
width:200px;
border:1px solid red;
display:flex;
margin:5px;
}
.box > div {
border:2px solid;
height:50px;
}
<div class="box">
<div style="width:300px"></div>
</div>
<div class="box">
<div style="min-width:300px;max-width:300px;"></div>
</div>
正如您在第二种情况下看到的那样,元素不会收缩,因为与 width
不同,min-width
会阻止这种情况。
另一种情况是使用 resize
属性:
div {
border: 2px solid;
height: 50px;
overflow: auto;
resize: both;
}
<div style="width:300px"></div>
<div style="min-width:300px;max-width:300px;"></div>
如您所见,我们可以调整 width
定义的元素的大小,而不是 min-width
/max-width
定义的元素的大小
我们还应该注意到 min-width
/max-width
比 width
更强大。将 3 个属性设置为不同的值将使 min-width
成为赢家
.box {
border: 2px solid;
height: 50px;
width:100px;
min-width:200px;
max-width:150px;
}
<div class="box"></div>
这意味着我们可以使用 min-width
/max-width
覆盖由 width
设置的值,但不能相反
关于css - min-width 和 max-width 具有相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50707254/