为什么这个媒体查询不起作用?

Why is this Media Query not working?

我觉得我马上就会觉得自己很傻,但我终究无法弄清楚我的媒体查询出了什么问题。我正在使用 Adob​​e 的 Brackets 作为我的代码编辑器,最初认为程序中存在故障。但是后来我在 jsFiddle 中测试了代码,它在那里也不起作用,所以我一定是在用代码捏造一些东西。

谁能看出哪里出了问题?

这是我的jsFiddle

HTML

<div class="helpful">

<span class="thumb">Did you find this helpful?</span>
<span class="readers">82 Readers found this helpful</span>

</div>

CSS

.helpful .readers {
    color: #35cb1a;
    font-size: .9em;
}

.helpful .thumb {
    float: right;
    color: #7b7b7b;
    font-size: .9em;
}

@media screen and (max-width: 1020px) {

    .helpful .readers,
    .helpful .thumb {
        display: block;
        margin: auto;
     }
 }

display: block; margin: auto 对没有指定宽度的元素无效,因为 blocks with auto width stretch to the full width of their container leaving no room for margins.

此外,自动边距对浮动元素没有影响,a floated element is display: block by definition

所以你的媒体查询是有效的,但其中的样式对给定的布局没有任何明显的影响。

  • 如果您希望浮动元素在 1020 像素和更窄处停止浮动,您需要重写 float 声明。
  • 如果您希望文本居中,请使用 text-align: center 而不是 margin: auto
  • 如果你想让两个元素垂直堆叠,保持display: block声明。

Putting it all together:

@media screen and (max-width: 1020px) {
    .helpful .readers,
    .helpful .thumb {
        display: block;
        text-align: center;
    }

    .helpful .thumb {
        float: none;
    }
}

你的代码非常好,因为你想在一些 1020px 宽度之后将那些 div 居中对齐,为此你使用了这个 css

@media screen and (max-width: 1020px) {

    .helpful .readers,
    .helpful .thumb {
        display: block;
        margin: auto;
     }
 }

但是如果你使用margin:auto,你总是需要提到width

我假设宽度为 200px 所以 css 应该是这样的

@media screen and (max-width: 1020px) {

    .helpful .readers,
    .helpful .thumb {
        display: block;
        margin: auto;
        widht:200px;
     }
 }

在这个fiddlehttps://jsfiddle.net/vgrtety9/3/

中工作正常