skip to Main Content
.cards {
    width: 'window.screen.height / 15 or whatever' + px;
    height: '.cards.width * 1.5' + px;
}

I have this code, I want to set the width of the cards class to a percent of the screen size in some way.

I don’t want to edit the size of each individual element of the class because I think it would take more processing power. Instead, I want to change the entire class so that the next element I create for that class will have these updated attributes, is there any easy way to do this?

I tried inserting a script tag in the style sheet, but that just made me feel stupid so I asked chatGPT and it couldn’t understand what the problem was, so I got no help there either.

2

Answers


  1. You can just use CSS:

    .cards {
        width: calc(100vh / 15);
        aspect-ratio: 2 / 3;
    }
    

    vh is 1 percent height of viewport (vw 1 % of width of viewport)

    Login or Signup to reply.
  2. Although the current task (querying screen height) is achievable using just CSS too, it’s not impossible to modify CSS with JavaScript. In fact, you can introduce variables in CSS as well, which you can later manipulate.

    function changeScreenHeightTo (newHeight) {
      document.documentElement.style.setProperty('--screen-height', newHeight + 'px');
    }
    
    function changeBackgroundColorTo (newColor) {
      document.documentElement.style.setProperty('--background-color', newColor);
    }
    :root {
        --screen-height: 100px;
        --background-color: red;
    }
    
    .cards {
        --cards-width: calc(var(--screen-height) / 15);
        --cards-height: calc(var(--cards-width) * 1.5);
        width: var(--cards-width);
        height: var(--cards-height);
        aspect-ratio: 2 / 3;
        background-color: var(--background-color);
        margin: 20px 0;
    }
    <div class="cards"></div>
    
    <div>
      <button onclick="changeScreenHeightTo(window.screen.height)">
        Change --screen-height variable to window.screen.height
      </button>
    
      <button onclick="changeScreenHeightTo(567)">
        Change --screen-height variable to 567px
      </button>
    </div>
    
    <div>
      <button onclick="changeBackgroundColorTo('green')">
        Change --background-color variable to green
      </button>
    
      <button onclick="changeBackgroundColorTo('#555')">
        Change --background-color variable to #555
      </button>
    </div>

    You can influence the attributes of any DOM element (style="...") by querying the element and using the setProperty function within the style property. I’ve declared variables in the root element, so modifying them can be easily achieved through the style property of the document.documentElement root element.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search