Html CSS 媒体查询问题(滚动条)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8146874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:32:01  来源:igfitidea点击:

issue with CSS media queries(scrollbar)

htmlcssbrowser

提问by anil tiwari

I am having problem with css media query in Firefox. It works correct in Chrome like I made two DIVs and want a scrollbar. If I decrease the screen size of firefox upto 800px then both DIVs collapse and after some pixels media query works but that not happens in Chrome.

我在 Firefox 中遇到 css 媒体查询问题。它在 Chrome 中工作正常,就像我制作了两个 DIV 并想要一个滚动条。如果我将 firefox 的屏幕尺寸减小到 800 像素,那么两个 DIV 都会崩溃,并且在一些像素媒体查询工作后,但在 Chrome 中不会发生这种情况。

check this fiddle http://jsfiddle.net/RMvqC/2/

检查这个小提琴http://jsfiddle.net/RMvqC/2/

采纳答案by sandeep

Firefox & Webkit based browsers render the scrollbar differently. In Firefox, MediaQuery considered width of scrollbar which is 15px with the screen width, but in Webkit based browsers it's not considered scrollbar with the screen width. So, that's why the floated DIVs are collapsed in Firefox.

基于 Firefox 和 Webkit 的浏览器以不同的方式呈现滚动条。在 Firefox 中,MediaQuery 将滚动条的宽度视为 15px 与屏幕宽度,但在基于 Webkit 的浏览器中,它不被视为与屏幕宽度的滚动条。所以,这就是浮动的 DIV 在 Firefox 中折叠的原因。

I did some stuff with css may be that's help you. (check this fiddle)

我用 css 做了一些东西可能对你有帮助。(检查这个小提琴

        html {
            /* force scrollbars */
            height: 101%;
        }
        body {
            margin: 0; 
            padding:0; 
            white-space:nowrap; 
        }  
        #box1,
        #box2 {
            display:inline-block;
            width: 400px;
            height: 200px;  
            vertical-align:top;
            white-space:normal;
        }
        #box1 {
            background: #ce0000;
             margin-right:-5px;
        }
        #box2 {
            background: #8e0000;
        }

        @media screen and (max-width: 799px) { 
            body { 
                white-space:normal; 
            }
            #box1,
            #box2 {
                width: 300px;
            }
        }

回答by user3245967

I SOLVED this issue by calling the "mqGenie" javascript in the head of my project.

我通过在我的项目的头部调用“mqGenie”javascript 解决了这个问题。

Now the widths of my media queries work fine ( with the same value ) on Chrome, Safari, Firefox and IE with or without scroolbars.

现在我的媒体查询的宽度在 Chrome、Safari、Firefox 和 IE 上都可以正常工作(具有相同的值),无论是否带有滚动条。

This javascript Adjusts CSS media queries in browsers that include the scrollbar width in the viewport width so they fire at the intended size.

此 javascript 调整浏览器中的 CSS 媒体查询,包括视口宽度中的滚动条宽度,以便它们以预期大小触发。

You can download it from this url:

你可以从这个网址下载:

http://stowball.github.io/mqGenie/

http://stowball.github.io/mqGenie/

回答by pixelfreak

Firefox & Opera follows W3C spec which is to include scrollbar width in media queries width (the reason might be to avoid infinite loop as described in a comment here), while Webkit does not (possibly coz they think it makes no sense)

Firefox 和 Opera 遵循 W3C 规范,即在媒体查询宽度中包含滚动条宽度(原因可能是为了避免此处评论中描述的无限循环),而 Webkit 则没有(可能是因为他们认为这没有意义)

There is a workaround (I've only tested this on FF), apparently if you force scrollbar to be visible all the time, then the width will now be consistent with Webkit. Here's the code:

有一个解决方法(我只在 FF 上测试过),显然如果你强制滚动条一直可见,那么宽度现在将与 Webkit 一致。这是代码:

html
{
   overflow:hidden;
   height:100%;
}
body
{
   position:relative;
   overflow-y:scroll;
   height:100%;
   -webkit-overflow-scrolling:touch; /* So iOS Safari gets the inertia & rubber-band effect */
}

If you want to apply this to FF & Opera only, you can resort to CSS hacks:

如果您只想将其应用于 FF 和 Opera,则可以求助于 CSS hacks:

/* Firefox */
@-moz-document url-prefix()
{
    html
    {
        overflow:hidden;
        height:100%;
    }
    body
    {
        position:relative;
        overflow-y:scroll;
        height:100%;
        /*-webkit-overflow-scrolling:touch;*/
    }
}

/* Opera */
x:-o-prefocus, html
{
    overflow:hidden;
    height:100%;
}
x:-o-prefocus, body
{
    position:relative;
    overflow-y:scroll;
    height:100%;
}

It goes without saying, the caveat is the scrollbar will be visible at all times, which might be an okay compromise.

不用说,需要注意的是滚动条将始终可见,这可能是一个不错的妥协。

回答by Daniel De León

Play safe!

玩得安全!

My final strategy is added 20px to the media queries and that is my default white space on the layout.

我的最终策略是向媒体查询添加 20px,这是我在布局上的默认空白。

With one exception: @media (min-width: 320px)At that size a don't leave the 20px white space and include one more rule to solve minor background issues:

有一个例外:@media (min-width: 320px)在该尺寸下,不要留下 20px 的空白区域,并包含另一个规则来解决次要的背景问题:

html body {
    min-width: 320px;
   }

20px is the scroll bar default width size.

20px 是滚动条默认宽度大小。

FYI: https://www.sitepoint.com/rwd-scrollbars-is-chrome-better/

仅供参考:https: //www.sitepoint.com/rwd-scrollbars-is-chrome-better/

回答by Ich_73

Short Answer

简答

If you do not want to display the scrollbar all the time, wrap your content into <div>elements etc. you can use JavaScript to add a certain value to all media queries when the scrollbar is shown.

如果您不想一直显示滚动条,请将内容包装到<div>元素等中。您可以使用 JavaScript 在显示滚动条时为所有媒体查询添加某个值。

// check whether scrollbar is visible
var isScrollbarVisible = window.innerWidth > document.documentElement.clientWidth;

// search for media rule
var mediaRule = document.styleSheets[i].cssRules[j];

// update media rule
mediaRule.media.mediaText = '..'



Long Answer

长答案

I wrote a small script which you can include on your page. It detects when the window is resized and changes all media queries if needed. The value of the css variable --replace-media-scrollbaris used as the width of the scrollbar or 15pxif no value was found. This works for the media queries with, min-width, max-width, height, min-heightand max-heighteven when they are connected using and.

我写了一个小脚本,您可以将其包含在您的页面中。它检测窗口何时调整大小并在需要时更改所有媒体查询。css 变量的--replace-media-scrollbar值用作滚动条的宽度,或者15px如果没有找到值。该方法适用于媒体查询withmin-widthmax-widthheightmin-heightmax-height即使他们使用连接and

JavaScript:

JavaScript:

function* visitCssRule(cssRule) {
    // visit imported stylesheet
    if (cssRule.type == cssRule.IMPORT_RULE)
        yield* visitStyleSheet(cssRule.styleSheet);

    // yield media rule
    if (cssRule.type == cssRule.MEDIA_RULE)
        yield cssRule;
}

function* visitStyleSheet(styleSheet) {
    try {
        // visit every rule in the stylesheet
        var cssRules = styleSheet.cssRules;
        for (var i = 0, cssRule; cssRule = cssRules[i]; i++)
            yield* visitCssRule(cssRule);
    } catch (ignored) {}
}

function* findAllMediaRules() {
    // visit all stylesheets
    var styleSheets = document.styleSheets;
    for (var i = 0, styleSheet; styleSheet = styleSheets[i]; i++)
        yield* visitStyleSheet(styleSheet);
}

// collect all media rules
const mediaRules = Array.from(findAllMediaRules());

// read scrollbar width
var style = getComputedStyle(document.documentElement);
var scrollbar = style.getPropertyValue('--replace-media-scrollbar') || '15px';

// update media rules
if (scrollbar != '0px') {
    var oldValue = '0px';
    function updateMediaRulesScrollbar() {
        var newValue = window.innerWidth > document.documentElement.clientWidth ? scrollbar : '0px';
        // if value changed
        if (oldValue != newValue) {
            for (var i = 0, mediaRule; mediaRule = mediaRules[i]; i++) {
                var regex = RegExp('\((width|min-width|max-width|height|min-height|max-height): (calc\([^)]*\)|[^)]*)\)', 'g');
                var replacement = '(: calc( - ' + oldValue + ' + ' + newValue + '))';
                mediaRule.media.mediaText = mediaRule.media.mediaText.replace(regex, replacement);
                console.log(mediaRule);
            }
        }
        oldValue = newValue;
    }
    updateMediaRulesScrollbar();
    window.onresize = updateMediaRulesScrollbar;
}

Optional CSS:

可选的 CSS:

:root {
  --replace-media-scrollbar: 15px;
}

回答by AvL

You can implement a solution for Firefox pretty easily by using a CSS-hack. After wrapping your content in an extra <div>add this lines to your CSS:

您可以使用 CSS-hack 非常轻松地为 Firefox 实现解决方案。在额外包装您的内容后,<div>将此行添加到您的 CSS:

/* Firefox-Hack */
body,  x:-moz-any-link {
    overflow-x: hidden;
}
#wrapper,  x:-moz-any-link {
    margin: 0 -7.5px;
}

Check the jsbin(jsfiddle is down right now)

检查jsbin(jsfiddle 现在已关闭)

To have richer responsive experience you could add another media query: another jsbin

为了获得更丰富的响应体验,您可以添加另一个媒体查询:another jsbin

The CSS-hack was found at paulirish.com

CSS-hack 是在paulirish.com 上找到的

回答by Joshua Barker

This is peripherally related, but I found a way to detect which media-query the browser is actually using at any given moment, without having to muck around with scrollbar and body widths...

这是外围相关的,但我找到了一种方法来检测浏览器在任何给定时刻实际使用的媒体查询,而无需处理滚动条和主体宽度......

Basically, define a an absolutely positioned 1-x-1-pixel-sized list somewhere in your body, with a list-item for each media-query condition you want to be "watchable".

基本上,在您的身体某处定义一个绝对定位的 1-x-1 像素大小的列表,并为您希望“可观看”的每个媒体查询条件设置一个列表项。

Then in each media-query definition, show/hide the corresponding list-item, and then simply check whether that item is visible from within your script.

然后在每个媒体查询定义中,显示/隐藏相应的列表项,然后简单地检查该项目是否在您的脚本中可见。

Example:

例子:

<body>
    ...
    <ul id="mediaQueryHelper">
        <li id="desktop"></li>
    </ul>
</body>

<style type="text/less">
    #mediaQueryHelper {
        position: absolute;
        height: 1px;
        width: 1px;
        visibility: hidden;
        top: -999px;
        left: -999px;
    }

    @media screen and (min-width: 481px)
    {
       #desktop { display: inline; }
    }

    @media screen and (min-width: 320px) and (max-width: 480px)
    {
       #desktop{ display: none; }
    }

</style>

<script type="text/javascript">
    $(document).ready(function()
    {
        var _desktop = $("#desktop");

        $(window).resize(function() {
            console.log("media-query mode: " + _desktop.is(":visible") ? "DESKTOP" : "MOBILE");
        });
    });
</script>