Adaptable div arrangement

Currently, I am working on a layout that includes a toolbar and a main div. In my design, the positioning of the toolbar should change based on the window's dimensions. If the Y axis is smaller than the X axis, the toolbar needs to be on the left side. Conversely, if the X axis is smaller than the Y axis, the toolbar should be placed at the top. However, despite my efforts to position the toolbar absolutely at the top: 0 and left: 0, and adjusting the width and height properties upon resizing, my code does not seem to be functioning correctly.

Javascript:

window.onresize = function(event) {
winW = window.innerWidth;
winH = window.innerHeight;   
console.debug("x axis:" + winW  + "y axis:" + winH);

if(winW < winH){
   var elem = document.getElementById('div1');

    console.debug("test" + elem.style.width);

   var a = elem.style.height;
   elem.style.height = elem.style.width;
   elem.style.width = a;

}
else{
   var elem = document.getElementById('div1');

    elem.style.height = elem.style.height;
    elem.style.width = elem.style.width;
}
}

CSS:

#div1{
  background: red;
  position:absolute;
  height:100%;
  width:20px;
  top:0;
  left:0;
}
#div2{
  width:100%;
  height:500px;
  background-color:green;
  margin-left: 20px;
}

Check out this jsFiddle example for reference.

Answer №1

To achieve this, you can utilize the

@media screen and (min-aspect-ratio: 1/1) { ... }
CSS query. This will apply styles only when the width of the window is equal to or greater than its height.

Check out the DEMO for a live example.

I've implemented the code below by eliminating JavaScript:

@media screen and (min-aspect-ratio: 1/1) { 
    #div1 {
        width: 100%;
        height: 20px;
    }

    #div2 {
        width: 100%;
        margin: 0;
     }                
}

For detailed information on Media Queries, refer to MDN's documentation.

To ensure compatibility across different browsers, take a look at the support for Media Queries. Additionally, if JavaScript is an option, consider using Respond.js to extend support for all users.

Answer №2

Make sure to give an upvote if you like the media ratio ;)

Ensuring compatibility across different browsers:

window.onresize = function(event) {
    winW = window.innerWidth;
    winH = window.innerHeight;

    console.debug("x axis:" + winW  + "y axis:" + winH);

    document.getElementById("div1").className = ( winW < winH ? "verticalMenu" : "horizontalMenu" );
}

// You can also manually invoke window.resize() once to set it as default behavior. Alternatively, set a defaultClass on the div itself in the HTML

Additionally,

.horizontalMenu {
    height:20px;
    width:100%;
}
.verticalMenu {
    height:100%;
    width:20px;
}

For reference, check out this CodePen link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to showcase an image with Angular 2?

Just starting out with Angular 2 and ran into an issue while trying to display an image using a relative path. <img src="./../images/publicVideo1.PNG"> Unfortunately, I encountered the following error: null:1 GET http://localhost:4200/null 404 (No ...

Employing the Confirm() function within the onbeforeunload() event

Is there a way to prompt the user with a confirmation box before exiting a page using JavaScript? If the user clicks "OK", a function should be executed before leaving the page, and if they click "Cancel", the page should remain open. window.onbeforeunloa ...

Utilizing JSON to transfer PHP array data for display using JQuery

Currently, I am working on a jQuery script that is responsible for fetching a PHP array from the MySQL database and converting it into a JSON object. The process is functioning correctly, as I can successfully output the raw JSON data along with the keys. ...

Achieving Vertical Alignment in a Bootstrap 4 Image Overlay Card

I am facing a challenge in trying to vertically center a FontAwesome icon within an Image Overlay Card. Despite attempting various methods like using d-flex and justify-content-center, none of them seem to be effective. What could I be overlooking? < ...

What is the connection between serialization and JSON?

Can you explain serialization? Serialization is the process of converting an object into a stream of bytes, allowing it to be sent over a network or stored in a file. This allows the object to be reconstructed later on. What exactly is JSON? JSON stands ...

Creating a Stylish Funnel Graph using CSS

I am currently working on customizing a funnel chart based on data from my database that is displayed on the page. Everything is functioning correctly except for the CSS rendering of the chart. <ul id="funnel-cht"> <li style="height:70px;widt ...

What are the different scenarios in AngularJS where $scope is utilized versus when var is utilized?

Which is more efficient in AngularJS: using var or $scope. for variables inside functions? I am asking this question because I recently came across information about $watch, $digest, and $apply in AngularJS. While I may not have fully grasped the concept ...

"Troubleshooting: Why isn't my Tailwindcss box shadow

I'm currently incorporating Tailwindcss into a React project to recreate the Star Wars website mobile menu. However, I am facing an issue where the box shadow added to the hamburger icon segments is not visible when the navigation drawer is opened. A ...

Troubleshooting: Custom checkbox using CSS ::before does not display properly on Firefox and Edge browsers

Encountering a frustrating CSS challenge while working on a project that needs to be compatible across various browsers. Specifically, I'm having issues with custom styling for checkboxes. Despite following recommendations to use a ::before pseudo-ele ...

Showing the ng-controller contents post executing AJAX request using the "as" method

My goal is to display the contents of ng-repeat after making an AJAX call using $http. <table ng-controller="TableController as tc"> <tr> <th>Date</th> <!-- other headers are here --> ...

The .val() and focus() methods are not functioning correctly

I am having an issue with a simple script: when I input a link to an image in the form's INPUT field, it should automatically display a preview of the image: https://example.com/image.jpg However, when I input the same link not by using ctrl+C/ctr ...

Having an issue where my meshes disappear when using the Unreal Bloom render pass in ThreeJS. Any ideas on what might be causing

Just starting out with Three and I'm really enjoying it, but I seem to be stuck on a problem. The code in this gist might help: https://gist.github.com/TheeBryanWhite/a7a2041fc8848a0ba449897883c43bdc Initially, the first render functions correctly b ...

Maintaining fixed panels as you scroll through a centrally aligned layout

I am looking to create a layout with three divs set up as columns. The outer two will be for navigation and need to stay in place while the user scrolls, but the middle section will contain content that should scroll normally along with the page. I know t ...

The close button on my modal isn't functioning properly

There seems to be an issue with the close button functionality. <div class="modal fade show " id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" style="display: block;left: -6.5%;"> <div class="modal-dialog" ...

Picture not adapting correctly to various screen sizes

I'm looking to adjust the size of an image based on the user's browser window. Here is the code I have so far: .image { max-height: 15%; width: auto; } The image class is used in this section of my code: <ul> <li> <img c ...

Tips for displaying a Bootstrap 4 table on smaller screens

I have a Bootstrap 4 table filled with JSON data. The table renders perfectly on the UI, but users on smaller devices must scroll to view all the data. Despite there not being much data in the HTML table, users still need to scroll on small devices. I wa ...

Manipulating Object origin data

I'm unsure if this can be achieved. I am aiming to create a header and footer that remain the same while only switching the content pages. The resources I have at my disposal cover HTML, JS, CSS, and JQuery. Below is a simplified version of my curre ...

Using the i18next Module for Localization in ExpressJS and Front-End Development

I am currently integrating the i18next module into my NodeJs/ExpressJS web application. All the translation files are stored in the /locales directory. According to information from i18next.com, it can also be utilized on the client side. <script typ ...

Develop an HTML table using either JSON or jQuery in Javascript

JavaScript is a bit of a mystery to me right now - I could really use some assistance in overcoming this obstacle that has me pulling my hair out! I'm struggling with constructing HTML code using JSON data. It's just not clicking for me at the m ...

Creating a smooth entrance effect in VueJS using CSS transitions is a breeze

Even though it seems simple, I am struggling to get it to work properly. My goal is to have the existing elements in my list shift to make room for a new element added, and then have the new element appear with a smooth fade transition. I have tried to im ...