Let's say that we have body width of page set to 2000px with content centered horizontally inside of body with width set to 1200px.
<body>
<div class="content"></div>
</body>
CSS:
body {
width: 2000px;
}
.content {
position: relative;
width: 1200px;
margin-left: auto;
margin-right: auto;
}
What I am trying to achieve is that I do not allow horizontal scrolling at all until your window size is 1200px or less (on resize) with setting overflow-x to hidden.
$(function() {
$(window).resize(function() {
if(window.innerWidth > 1200) {
$("body").css({
"overflow-x": "hidden"
});
} else {
$("body").css({
"overflow-x": "visible"
});
}
});
});
which works fine. But I also want to prevent user from scrolling further than 1200px if his window width is less than 1200px (problem here is that as soon as the window width is less than 1200px, it is possible to scroll to full width - 2000px).
So how would you solve this?
Let's say that we have body width of page set to 2000px with content centered horizontally inside of body with width set to 1200px.
<body>
<div class="content"></div>
</body>
CSS:
body {
width: 2000px;
}
.content {
position: relative;
width: 1200px;
margin-left: auto;
margin-right: auto;
}
What I am trying to achieve is that I do not allow horizontal scrolling at all until your window size is 1200px or less (on resize) with setting overflow-x to hidden.
$(function() {
$(window).resize(function() {
if(window.innerWidth > 1200) {
$("body").css({
"overflow-x": "hidden"
});
} else {
$("body").css({
"overflow-x": "visible"
});
}
});
});
which works fine. But I also want to prevent user from scrolling further than 1200px if his window width is less than 1200px (problem here is that as soon as the window width is less than 1200px, it is possible to scroll to full width - 2000px).
So how would you solve this?
Share Improve this question asked Apr 1, 2014 at 0:39 Matúš DúbravaMatúš Dúbrava 8011 gold badge7 silver badges19 bronze badges 4-
So basically you want the content to be fixed at
1200px
, with amargin-left
of400px
, until one gets down to a screen size of1200px
? – Kelderic Commented Apr 1, 2014 at 0:44 - No, I don't want margin-left to be set to 400px, it is set to auto so that the content is always centered. – Matúš Dúbrava Commented Apr 1, 2014 at 0:47
- Don't use JS to hijack the scroll event, but instead set the element's width to 1200px so users cannot scroll further. – Terry Commented Feb 10, 2023 at 9:23
- 1 It seems that this can be handled by media queries. Have you tried any? – Naeem Akhtar Commented Nov 15, 2024 at 6:08
2 Answers
Reset to default 0If I understand your question correctly then I believe this could be fixed by adding a max width style to your body tag. This eliminated side scroll for me.
body {
max-width: 2000px;
}
In this case you can use the scrollLeft proprerty:
onScroll = function (e){
var maxScroll=1200
if(e.target.scrollLeft>maxScrollLeft){
e.target.scrollLeft=maxScrollLeft
}
}