CSS dynamic max width

2019-08-25 07:23发布

I'm making a memory game with cards and I got a little problem with centering. Each card that gets printed is 192px by 192px, with a margin of 1.5px for all sides, so 1 card = 192 + 1.5 + 1.5 = 195px in width. All of the cards display as inline-block, so when there is not enough space to print another card in one row, it prints it on the next one. The problem I am encountering right now is that the carddeck doesn't center because the width of the carddeck exceeds the amount of width that the cards of one row have. I basically want to change the max width of the card deck to the amount of width the cards of one row make.

Example:

On a fully sized window it displays 8 cards in a row (= 1560px width) so I want

.card-deck {
  max-width: 1560px;
  position: absolute;
  left: 0;
  right: 0;
  margin-left: auto;
  margin-right: auto;
}

On a resized window it displays 6 cards in a row (= 1170px width) so I want

.card-deck {
  max-width: 1170px;
  position: absolute;
  left: 0;
  right: 0;
  margin-left: auto;
  margin-right: auto;
}

So is there a way to make the max-width attribute change according to how many cards are in one row, using CSS? Something like max-width: card1-width + card2-width ...;.

Thanks in advance.

  • Ed

2条回答
▲ chillily
2楼-- · 2019-08-25 08:21

Yes, like this:

 .card-deck {
      position: absolute;
      left: 0;
      right: 0;
      margin-left: auto;
      margin-right: auto;
 }
 @media only screen and (max-width: 1170px) {
        .card-deck {
           max-width: 1170px;
        }
    }

 @media only screen and (max-width: 1560px) {
        .card-deck {
           max-width: 1560px;
        }
    }
查看更多
forever°为你锁心
3楼-- · 2019-08-25 08:29

I found the solution:

HTML:

<body onresize="carddecksize()">

Javascript:

function carddecksize() {
  var deck = document.getElementById("carddeck");
  if (window.innerWidth >= 1560) {
    deck.style.maxWidth = '1560px';
  }
  else if (window.innerWidth >= 1365) {
    deck.style.maxWidth = '1365px';
  }
  else if (window.innerWidth >= 1170) {
    deck.style.maxWidth = '1170px';
  }
  else if (window.innerWidth >= 975) {
    deck.style.maxWidth = '975px';
  }
  else {
    deck.style.maxWidth = '780px';
  }
}
查看更多
登录 后发表回答