【发布时间】:2017-07-08 22:56:24
【问题描述】:
我有一个奇怪的问题。我的 CSS 中的媒体查询规则以它们应该的特定宽度触发,但是如果我已经将浏览器窗口调整到那个较小的宽度,然后将浏览器窗口扩展到它之外,就会发生一些奇怪的事情。在我刷新页面之前,一切看起来都很正常。只有在页面刷新时,布局才会以意想不到的方式发生变化。目标当然是让媒体查询正常运行,因为页面刷新不应该改变任何规则。
我试图用简单的骨骼重现问题:
//CSS media queries added to style tag here to prevent scrolling in other code blocks
var style = document.getElementsByTagName('style')[ 0 ];
style.innerHTML +=
' \
@media( max-width: 550px ) { \
body { \
background-color: #ddd; \
transition: 1s; \
} \
main { \
height: auto; \
text-align: center; \
} \
.circle, .about-container { \
float: none; \
} \
.circle { \
display: inline-block; \
transform: translateY( 0 ); \
} \
.about-container { \
margin: 0 auto; \
text-align: left; \
} \
} \
@media( min-width: 551px ) { \
.circle { \
transform: translateY( 0 ); \
} \
} \
';
/* ///////////////// ELEMENTS IN ORDER THEY APPEAR IN HTML ///////////////// */
* {
box-sizing: border-box;
}
main {
max-width: 600px;
height: 11rem;
margin: 0 auto;
padding-top: 10px;
font-size: 0.8rem;
text-align: left;
}
.circle {
width: 100px;
height: 100px;
background-color: #444;
border-radius: 50%;
float: left;
top: calc( 50% - 10px );
}
.about-container {
width: 75%;
float: right;
}
body button {
display: block;
margin: 0 auto;
padding: 8px;
}
<head>
<style>
/* ///////////// BASIC STYLES TO MAKE THIS SNIPPET LOOK BETTER ///////////// */
@import url('https://necolas.github.io/normalize.css/latest/normalize.css');
.clearfix:after {
content: "";
display: block;
clear: both;
}
.vertically-center {
position: relative;
top: 50%;
transform: translateY( -50% );
}
</style>
</head>
<body>
<main class="clearfix">
<div class="circle vertically-center"></div>
<div class="about-container">
<h3>About</h3>
<p>
This problem is wierd. When <strong>snippet is made full screen</strong>
and browser width is shrunk to less than <strong>550px</strong> <em>
( You will know you're at 550px because the background will darken )</em>
the layout changes - as expected. However when window is expanded beyond
550px again and <strong>Reload Frame</strong> is clicked the layout
unexpectedly updates itself. <br><br>What's going on?
</p>
</div>
</main>
<button onclick="location.reload()">Reload Frame</button>
</body>
虽然很奇怪,但我觉得这有一个简单的解决方案,我希望?
编辑:我在 chrome 浏览器上看到了这些结果。将上传一个 GIF 来演示我在下面看到的内容。
【问题讨论】:
-
你 1) 翻到整页 2) 缩小宽度直到背景变暗。 3)扩大宽度,直到背景为白色。 4) 点击按钮?
-
你用的是什么浏览器?
-
铬。我正在上传一个 gif 来演示我所看到的。
-
@MrLister 我的问题不是 JavaScript 问题。这是刷新时触发的 CSS 媒体查询。这里的 JavaScript 仅用于这个演示。
-
@L.S 请查看带有显示我的问题的 gif 更新。
标签: css google-chrome css-float media-queries