关于CSS的min-width属性的注意点

261 阅读1分钟

最近在做样式布局的时候遇到了一个问题:


代码:

<div class="box1">
  <div class="box2"></div>
</div>
<style lang="scss">
.box1{
  width: 200px;
  height: 100px;
  background-color: #cfc;
  .box2{
    min-width:300px;
    width: 100% !important;
    height: 100px;
    border: 1px solid #000;
  }
}
</style>

结果:

box.png
从运行的结果可以看出,虽然box1这个父盒子的width是100px,且box2的width设置为100%,但是由于box2的min-width是300px,就会导致box2的宽度比box1大,并不等于box1的宽度。
由此可以得知,min-width的优先级是比width高的,其实max-width也一样比width的优先级高、min-height和max-height的优先级也比height高。
还有就是,虽然我在box2的width属性上添加了!important,但它的作用是使其优先于其他具有相同选择器和样式属性的规则,并不能影响到min-width


题外话:
不过想想也是,min-width、max-width、min-height和max-height,这些属性规定了盒子的宽高最小最大应该是多少,样式自然要遵循这一规则。