سؤال

Which one of these is a "better CSS code" in terms of best practise?

A - rewriting:

@media only screen and (min-width: 480px) and (max-width: 960px) {
  h1, h2, .header, .widget, .copyright {
    position: static;
    width: 100%;
    height: auto;
    /* a lot more styles may be here */
  }
  .copyright {position: relative;}
}

B - repetition:

@media only screen and (min-width: 480px) and (max-width: 960px) {
  h1, h2, .header, .widget {
    /* CLASS .copyright is missing here to avoid rewriting */
    position: static;
    width: 100%;
    height: auto;
    /* a lot more styles may be here */
  }
  .copyright {position: relative; width: 100%; height: auto; /* a lot more of the SAME styles may be here */}
}

Can rewriting have some negative impact (exhibit A)? Slower rendering, problems in older browsers..? I don't know why, but it doesn't seems right to me - although it is easier to do.

هل كانت مفيدة؟

المحلول

Speed could be a minor issue, but the overall concern would be the readability of your code. Going forward, you or someone else wants to edit, easier to make changes to A that carry over rather then B.

نصائح أخرى

I would probably pick option A. I say probably because it depends on how much sense it makes to do so.

Performance wise, the difference between the two options is negligible. The important part is that it makes sense. If you're in a situation down the line where that 100% width needs to change to 95% you'll be glad you went with the first option.

It's odd that in A) you're specifying position for .copyright, only to immediately override it. Perhaps a minor nit, but it would be cleaner to do

h1, h2, .header, .widget, .copyright {
  width: 100%;
  height: auto;
}
h1, h2, .header, .widget {
  position: static;
}
.copyright {
  position: relative;
}

However, you could also consider factoring the width: 100%; height: auto; part into a separate class with a semantic name, such as full-width. That way, you avoid polluting h1 globally. You would write:

.full-width {
  width: 100%;
  height: auto;
}
h1, h2, .header, .widget {
  position: static;
}
.copyright {
  position: relative;
}

and then

<h1 class="full-width">My Header<h1>
<div class="copyright full-width">(c) 2013 Joudicek</div>

As other posters have mentioned, performance is the least of your worries. Get the structure right, then if you really want to you can do some CSS performance profiling and do whatever tweaking is called for.

It is always good practice to write short code so i am recommending you First(A) option over Second (B).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top