I am using Twitter Bootstrap on a project. As well as the default bootstrap styles I have also added some of my own
//My styles
@media (max-width: 767px)
{
//CSS here
}
I am also using jQuery to change the order of certain elements on the page when the width of the viewport is less that 767px.
$(document).load($(window).bind("resize", checkPosition));
function checkPosition()
{
if($(window).width() < 767)
{
$("#body-container .main-content").remove().insertBefore($("#body-container .left-sidebar"));
} else {
$("#body-container .main-content").remove().insertAfter($("#body-container .left-sidebar"));
}
}
The problem I am having is that the width calculated by $(window).width()
and the width calculated by the CSS doesn't seem to be the same. When $(window).width()
returns 767 the css calculates it the viewport width as 751 so there seems to be a 16px different.
Does anyone know what is causing this and how I could solve the problem? People have suggested that the width of the scrollbar isn't being taken into considering and using $(window).innerWidth() < 751
is the way to go. However ideally I want to find a solution that calculates the width of the scrollbar and that is consistent with my media query (e.g where both conditions are checking against the value 767). Because surely not all browsers will have a scrollbar width of 16px?
The best cross-browser solution is to use Modernizr.mq
link: https://modernizr.com/docs/#mq
Modernizr.mq allows for you to programmatically check if the current browser window state matches a media query.
Note The browser does not support media queries (e.g. old IE) mq will always return false.
Use
This solved my problem
It may be due to
scrollbar
, useinnerWidth
instead ofwidth
likeAlso you can get the
viewport
likeAbove code Source
Check a CSS rule that the media query changes. This is guaranteed to always work.
http://www.fourfront.us/blog/jquery-window-width-and-media-queries
HTML:
Javascript:
CSS:
Workaround that always works and is synced with CSS media queries.
Add a div to body
Add style and change them by entering into specific media query
Then in JS check style that you are changing by entering into media query
So generally you can check any style that is being changed by entering into specific media query.