Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I hide an element in HTML on mobile or small windows?

I am setting up a website, and when I open it on mobile or resize the page too small, the logo at the top of the page resizes itself in a way that looks bad. It would be great if I could resize it to look good, but at this point I am running out of time and just want to make it disappear.

I have tried and failed to write JavaScript scripts to make it disappear. I can set the visibility to hidden, but I have no way to do this in a responsive way to the page getting resized and no way to detect if the webpage is too small to begin with. I have attempted to use the onresize DOM Event, but it doesn't seem to work.

Here is my attempt at getting HTML to use the JS function:

<a href="website.com" class="header_logo" id="main_logo" onresize="fixBar()">
<img src="image.png">
</a>

Here is the JS function (which is below all the HTML on the page) that is not working:

<script type="text/javascript">
function fixBar() {
  if (window.innerWidth < 400px) {
    document.getElementById("main_logo").style.visibility = "hidden";
  } else {
    document.getElementById("main_logo").style.visibility = "visible";
  }
}
</script>

But as you can see, I still don't know how to check in the first place if the window is sufficiently small.

Also, I am working under restrictions that make it very difficult to use jQuery. If that is my only option then I will use it, but I would really prefer not to. Thank you for the help!

like image 843
Ben Avatar asked Dec 17 '22 15:12

Ben


1 Answers

You can use CSS Media Query for responsiveness.

@media only screen and (max-width: 400px) {
  #main_logo {
    display: none;
  }
}
<a href="website.com" class="header_logo" id="main_logo">
  <img src="https://placeholder.pics/svg/200x50">
  <div>Any HTML element</div>
</a>

Here, when the window size is less than 400px the element with id="main_logo" will be removed.

Another CSS rule would be visibility: hidden;

There is a difference between display: none; and visibility: hidden; Check that out here

like image 135
pasanjg Avatar answered Mar 24 '23 09:03

pasanjg