In a project utilizing Twitter Bootstrap and custom CSS, discrepancies arise between the viewport width values determined by $(window).width() and media queries. Despite setting a media query breakpoint at 767px, $(window).width() consistently returns a value 16px less, resulting in an unexpected CSS calculation.
The primary reason for this discrepancy is the exclusion of the scrollbar width in the $(window).width() calculation. To account for this, it's recommended to use $(window).innerWidth(), which incorporates the scrollbar width. However, this approach may not be suitable if consistent behavior with the media query breakpoint is desired.
1. window.matchMedia() (Modern Browsers Only)
If you can support modern browsers excluding IE9, window.matchMedia() provides a seamless solution. It fully aligns with CSS media queries and ensures consistency between JavaScript and CSS.
2. Modernizr's mq Method
For broader browser support, Modernizr's mq method is a viable option. It emulates the behavior of window.matchMedia() for browsers that understand CSS media queries.
To implement Modernizr's mq method:
if (Modernizr.mq('(max-width: 767px)')) { //... } else { //... }
The above is the detailed content of Why Does $(window).width() Differ from Media Query Breakpoints?. For more information, please follow other related articles on the PHP Chinese website!