zaydek zaydek - 4 months ago 26
CSS Question

Better alternative to @media queries?

I'm using this now,

@media (max-width: 1024px) { #icons { border-radius: 0px } }
@media ( width: 1025px) { #icons { border-radius: 1px 1px 0px 0px } }
@media ( width: 1026px) { #icons { border-radius: 2px 2px 0px 0px } }
@media ( width: 1027px) { #icons { border-radius: 3px 3px 0px 0px } }
@media ( width: 1028px) { #icons { border-radius: 4px 4px 0px 0px } }
@media ( width: 1029px) { #icons { border-radius: 5px 5px 0px 0px } }
@media ( width: 1030px) { #icons { border-radius: 6px 6px 0px 0px } }
@media ( width: 1031px) { #icons { border-radius: 7px 7px 0px 0px } }
@media ( width: 1032px) { #icons { border-radius: 8px 8px 0px 0px } }
@media ( width: 1033px) { #icons { border-radius: 9px 9px 0px 0px } }


To generate a flexible border-radius, proportional to the client's window width. Though, this looks ridiculous.

How else can this be achieved? Thanks!

Answer

Perhaps use a little dynamic, DRY (Don't Repeat Yourself) coding with JS?

The following uses jQuery for convenience.

var win = $(window);
win.resize(function() {
  if(win.width() >= 1024) {
    var padding = win.width()-1024;
    $("#icons").css("border-radius", padding + "px " + padding + "px 0px 0px");
  }
}).resize();
#icons {
  height: 100px;
  width: 100px;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="icons">Try resizing the window to widths greater than 1024px.</div>

What it does:

  1. Caches $(window) to avoid multiple DOM queries (which are slow).
  2. Every time window resizes, call the function.
  3. If window width is in range (> 1024px), run code.
  4. Make border-radius string by calculating the necessary padding.
  5. Trigger function with resize() on load.