Manuel Ebert
Manuel Ebert

Reputation: 8509

Using em for responsive styles on things other than type

Sometimes I wish I could just change a single variable in a media query and

HTML:

<div id="wrap">
  <div class="child1"></div>
  <div class="child2"></div>
</div>

LESS (does not work):

@base: 1000px;

@media all and (max-width: 768px) {
  @base: 600px;
}

.child1 {
  // 500px normally, 300px on small screens
  height: 0.5 * @base;
}
.child2 {
  // 250px normally, 150px on small screens
  height: 0.25 * @base; 
  }

That of course doesn't work because at compilation time, @base is set and applied to all classes. However, I came across this dirty workaround:

LESS:

#wrap 
    {
    font-size: 1000px;
    @media all and (max-width: 768px) {
      font-size: 600px;
    }
    .child1 {
      // 500px normally, 300px on small screens
      height: 0.5em;
    }
    .child2 {
      // 250px normally, 150px on small screens
      height: 0.25em; 
      }
    }

Assuming I don't actually have any text in my elements (or text only occurs in leaf nodes and sets their font-size explicitly), are there any serious downsides of using this approach?

Upvotes: 0

Views: 195

Answers (1)

ScottS
ScottS

Reputation: 72261

I cannot attest for certain, but the proposed em method just seems too hacky for my taste (and it does not make the heights of the elements easily determined by the coder). I would recommend using the media queries as they are intended to be used, and just build a mixin to get the values, like so:

LESS

@base: 1000px;
@smallBase: 600px;

.childHeights(@base) {
  // 500px normally, 300px on small screens
  .child1 {
  height: 0.5 * @base;
  }
  // 250px normally, 150px on small screens
  .child2 {
    height: 0.25 * @base;
  }
}

@media all and (max-width: 768px) {
  .childHeights(@smallBase);
}

.childHeights(@base);

CSS Output

@media all and (max-width: 768px) {
  .child1 {
    height: 300px;
  }
  .child2 {
    height: 150px;
  }
}
.child1 {
  height: 500px;
}
.child2 {
  height: 250px;
}

Upvotes: 1

Related Questions