Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Auto-size for PNG icons defined in CSS

I’m defining PNG icons for use in buttons in CSS. How can I define .icon-test without hardcoding both height and width?

I’d like to define only one of them, and let the other one be inferred automatically, without having to manually care about the aspect ratio.

.icon {
  display: inline-block;
}

.icon-test {
  background-image: url(https://via.placeholder.com/32x15);
  width: 2em;
  height: 2em;
}

.button {
  background-color: black;
  color: white;
  padding: 0.2em 1em;
  display: flex;
  align-items: center;
  width: 8em;
  justify-content: space-between;
}
<a class="button"><i class="icon icon-test"></i> BUTTON</a>

Note: What’s the standard way to do this, in order to import a pack of icons, easily available with CSS classes e.g. <span class="icon icon-ok"></span>?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

My best advice is to use background sizing on the element as you have it. You can use contain to be sure that your icon images aren’t cropped, and set them to not repeat.

.icon {
  display: inline-block;
}

.icon-test {
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  background-image: url(https://via.placeholder.com/32x15);
  width: 2em;
  height: 2em;
  background-color: pink; /* for demo only */
}

.two {
  background-image: url(https://via.placeholder.com/15x32);
}

.button {
  background-color: black;
  color: white;
  padding: 0.2em 1em;
  display: flex;
  align-items: center;
  width: 8em;
  justify-content: space-between;
}
<a class="button"><i class="icon icon-test"></i> BUTTON</a>

<a class="button"><i class="icon icon-test two"></i> BUTTON</a>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading