I'm trying to implement some dynamic elements into my simple HTML page.
My page's structure is based on the following CSS:
.container {
display: grid;
grid-template-columns: 2% 13% 70% 15%;
grid-template-rows: 15px 100px auto 15px;
gap: 0px 0px;
grid-template-areas:
". . . ."
". . Top ."
". LeftMenu MyContent RightNotes"
". . Bottom .";
}
And I wrote the following jQuery code to essentially remove my side columns whenever the screen size is below a given value:
$(document).ready(function(){
var width = $(window).width();
if(width < 1200){
$(".LeftMenu").hide();
$(".RightNotes").hide();
document.getElementById("MyBody").style.gridTemplateColumns = "0% 1.5% 96% 1.5%";
}else{
$(".LeftMenu").show();
$(".RightNotes").show();
document.getElementById("MyBody").style.gridTemplateColumns = "2% 13% 70% 15%";
}
$(window).resize(function(){
var width = $(window).width();
if(width < 1200){
$(".LeftMenu").hide();
$(".RightNotes").hide();
document.getElementById("MyBody").style.gridTemplateColumns = "0% 1.5% 96% 1.5%";
}else{
$(".LeftMenu").show();
$(".RightNotes").show();
document.getElementById("MyBody").style.gridTemplateColumns = "2% 13% 70% 15%";
}
});
});
And it works as intended, but there's a small problem. Whenever I resize my browser to a smaller width (such that the if statement goes through), a horizontal bar appears. Here's how it looks before scaling it down:
This is how it looks before resizing down the width
And this is after narrowing it down to a smaller width.
Why is this happening? And how can I get rid of it?
All my grid-template-area CSS codes are as short as:
.Bottom { grid-area: Bottom; }
My guess is that I'm missing something in there, not sure.
Thanks for any help you may provide.
CodePudding user response:
Seems like a specific tag is triggering a horizontal overflow. You may first need to identify which component is causing this. Anyways, this might work as a temporal solution in your css:
* {
overflow-x: hidden;
/* Note that you can also try with 'visible' instead of 'hidden',
but this way it might not help you to find the specific
overflowing component. */
}
But please avoid applying this property to *
and find the specific component causing the body to overflow like that. Try to find the component triggering the overflow and decide what you want to do with it, and if it should not suppose to overflow, adjust the box of the specific container as it should and avoid using fixed sizes <3
CodePudding user response:
You don't need jQuery / JavaScript, only CSS.
Look at: @media
Or in your case:
/* DEFAULT STYLES: ( Mobile first approach )*/
.RightNotes,
.LeftMenu {
display: none;
}
#MyBody {
grid-template-columns: 0% 1.5% 96% 1.5%;
}
/* DESKTOP STYLES: */
@media (min-width: 1200px) {
.RightNotes,
.LeftMenu {
display: block; /* display: grid; ? or whatever is needed */
}
#MyBody {
grid-template-columns: 2% 13% 70% 15%;
}
}