문제

I am working on a layout that needs precise media query handling. One of my issues is the crossbrowser scrollbar width as it is different according to browsers and most (all of them?) include it in the window width.

As we can see in these 2 examples, the media queries don't act at the same window size with and without the vertical scrollbar :

  1. Test without scrollbar
  2. Test with scrollbar

In the first example, you can see the background color change exactly at 800/700/600px window width.
In the second examples with the scrollbar the colors change at :

  • Chrome and firefox : 779/679/579px
  • IE : 783/783/583px

That makes a difference of up to 21px.

Is there is a work around by ignoring the scrollbar in media queries and focus on the available width itself.
If not how do you handle this issue, do you fix a maximum width for the scollbar and include it in the media queries?

-- UPDATE --

I am searching for best practices/solution with CSS as I would like to avoid JS for this project.

도움이 되었습니까?

해결책 2

Eight years later (2023), container queries are supported in most browsers and come to the rescue!

Instead of using a media query (which, as you found, reports a window width including the scrollbar), we declare a 'containment context' on the html element

html{container-type:inline-size;}

... and then use a container query to get it's width (without the scrollbar):

@container(max-width:600px){
  body{background:gray;}
}

I've updated your example 'Test with scrollbar' using a container query approach (leaving html and javascript untouched).

다른 팁

Look this example: http://stowball.github.io/mqGenie/

It is working fine both in Firefox and in Chrome for me (with scrollbars).

You can download and read more about this plugin here: https://github.com/stowball/mqGenie (~2.2 kb)

One of sources: https://stackoverflow.com/a/21414947/2898694

Enjoy.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top