【问题标题】:Why use display: block in a media query to override display: flex?为什么在媒体查询中使用 display: block 来覆盖 display: flex?
【发布时间】:2020-08-30 23:38:10
【问题描述】:

我正在查看一些 HTML 代码,看起来像这样(总结):

html,
body {
  height: 100%;
  background: #1c1c1c;
}

header {
  background: #1c1c1c;
  display: flex;
}

.child {
  flex-grow: 1;
}

ul {
  display: flex;
}

li {
  flex-grow: 1;
}

@media only screen and (max-width:542px) {
  header div:nth-child(1) {
    display: block;
  }
}
<header>

  <div class="child">
    <img src="logo.png" />
  </div>

  <ul class="child">
    <li>About</li>
    <li>Services</li>
    <li>Gallery</li>
    <li>Contact</li>
  </ul>


</header>

css 底部第三行的display:block 无效,我发现自己想知道它的作用是什么?

【问题讨论】:

  • 您的代码示例什么都不做 header div:nth-child(1) { display: block;} 是该元素的默认值,并且永远不会变成弹性框。您可能错过了示例中的某些内容。无论如何,如果您不需要 flex-column 属性,从 flex 切换到 block 会很有用(例如:@media only screen and (max-width:542px) { header { display: block;} }..
  • @G-Cyrillus ,我在 .css 中将标头定义为 flex 容器?
  • 是的,但标题 div:nth-child(1) 不是。它只是一个 flex child 。如果您确实知道它:css-tricks.com/snippets/css/a-guide-to-flexbox 很方便。对于媒体查询切换显示:值也很常见;)
  • @G-Cyrillus,谢谢。我懂了。为什么在媒体查询中将显示从块更改为内联没有效果?

标签: html css flexbox


【解决方案1】:

这在代码中并不明显,因为似乎缺少部分。

但这是基本逻辑:

  • display: flex 将子元素排成一行
  • display: block 恢复垂直堆叠

因此,覆盖将您带出 flex 布局并返回标准块布局(其中 flex 属性无效)。

这种设置可以方便地从桌面切换到移动布局,以及其他用例场景。

为了便于说明,这是代码的简化版本:

.child {
  display: flex;
  justify-content: space-around;
}

@media (max-width:542px) {
  .child {
    display: block;
  }
}
<ul class="child">
  <li>About</li>
  <li>Services</li>
  <li>Gallery</li>
  <li>Contact</li>
</ul>

jsFiddle demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-02
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 2016-12-21
    • 2020-05-17
    相关资源
    最近更新 更多