css 试图有一个响应设计的项目使用媒体查询和flexbox,但它是行不通的

1tuwyuhd  于 4个月前  发布在  其他
关注(0)|答案(2)|浏览(46)
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  flex-direction: column;
}

.item {
  margin: 10px;
  border: 1px solid lightgray;
  border-radius: 10px;
  overflow: hidden;
  width: 100%;
}

@media screen and (min-width:700px) {
  .item {
    width: 50%;
  }
  .container {
    flex-direction: row;
  }
}

个字符
我期待一个响应式的设计,当屏幕低于700px时,项目应该是柱状的,当屏幕宽于700px时,项目应该是一行,它们的宽度应该是50%。然而,看起来只有width: 50%;适用。
这是一张图片:


的数据

6ovsh4lw

6ovsh4lw1#

您需要考虑.item元素的border-left-widthborder-right-widthmargin-leftmargin-right。在viewport宽度大于700px的代码中,每个.item元素占用以下水平空间量:

50% + 10px + 10px + 1px + 1px = 50% + 22px
 ↑      ↑      ↑     ↑     ↑
`width` │`margin-right`    │
        │            │     │
  `margin-left`      │`border-right-width`
                     │
          `border-left-width`

字符串
因此,对于宽度为50% + 22px的2个项目,这将是44px大于100%,宽度为.container,因此将继续以大于700px的视口宽度进行换行。
要使它们显示在同一行中,请考虑调整它们的width,通过从50%中减去此额外空间22px来补偿水平边框宽度和水平边距的额外空间:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  flex-direction: column;
}

.item {
  margin: 10px;
  border: 1px solid lightgray;
  border-radius: 10px;
  overflow: hidden;
  width: 100%;
}

@media screen and (min-width:700px) {
  .item {
    width: calc(50% - 22px);
  }
  .container {
    flex-direction: row;
  }
}
<div class="container">
  <div class="item">content</div>
  <div class="item">content</div>
</div>

的数据
或者,您可以在.container上应用flex-wrap: nowrap。这将通过缩小.item元素的宽度来强制它们显示在一行中:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  flex-direction: column;
}

.item {
  margin: 10px;
  border: 1px solid lightgray;
  border-radius: 10px;
  overflow: hidden;
  width: 100%;
}

@media screen and (min-width:700px) {
  .container {
    flex-direction: row;
    flex-wrap: nowrap;
  }
}
<div class="container">
  <div class="item">content</div>
  <div class="item">content</div>
</div>

的字符串

2g32fytz

2g32fytz2#

您正在使用min-width: 700px,这意味着媒体查询中的样式将在屏幕宽度至少为700px时应用。然而,您希望相反:您希望样式在屏幕宽度小于700px时应用。为此,您需要使用max-width: 700px
您正在使用flex-direction: column作为容器,这意味着项目将垂直堆叠。然而,您希望相反:您希望项目水平堆叠。为此,您需要使用flex-direction: row
您需要按如下方式更改介质查询和弹性方向值:

.container{
  display:flex;
  justify-content: center;
  align-items: center; 
  flex-wrap:wrap ;
  flex-direction: row; /* change this to row */
}
.item{
  margin: 10px;
  border: 1px solid lightgray;
  border-radius: 10px;
  overflow: hidden;
  width: 100%;
}
@media screen and (max-width:700px) { /* change this to max-width */
  .item{
   width: 50%;
  }
  .container{
   flex-direction: column; /* change this to column */
  }
}

字符串

相关问题