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 ><i ></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 ></span>
?
CodePudding user response:
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 ><i ></i> BUTTON</a>
<a ><i ></i> BUTTON</a>