0

I have a responsive input button, I want to add a background icon which should be always 10px margin to "Search" text?

.button {
  background-image: url("https://via.placeholder.com/100.svg");
  background-position: 45% center;
  background-repeat: no-repeat;
}
<input type="submit" value="Search" class="button">

If I add CSS like this, icon placement is changing based on screen width.
But I want the gap between icon and Search text should be only 10px in any resolution.
Thanks in advance!

Requirement Screenshot

Rajesh B
  • 39
  • 4
  • why not use a normal button instead where you can insert an image or icon tag and add a margin to the icon? – tacoshy Aug 05 '21 at 10:58
  • @tacoshy I don’t have any control on HTML, I have to manage it from only CSS. – Rajesh B Aug 05 '21 at 11:01
  • not going to work responsivly. a background image has no influence on the elements dimension. so you need a fixed calculation of how wide the background image will be and add a fixed padding to the input text. – tacoshy Aug 05 '21 at 11:02
  • Can you post screenshot of your requirement? – Nitheesh Aug 05 '21 at 11:03
  • the only possible solution is to use a font awesome icon: https://stackoverflow.com/a/11703274/14072420 – tacoshy Aug 05 '21 at 11:04
  • This can be achieved using `::before` selector, but it doesn't work on inputs. – TechySharnav Aug 05 '21 at 11:08
  • @Nitheesh added my requirement screenshot – Rajesh B Aug 05 '21 at 11:13
  • Simply set it to 10 px. But if what you want is to keep the fisical space as if you were measuring it from the outside of your screen and then if you change device when you measure this external space it keeps the same width, the, if it is useful for some unknown and mysterious thing, you'll have to create a code to calc that – SIMBIOSIS surl Aug 05 '21 at 13:30

1 Answers1

0

By using calc(), you won't have the problem of replacement based on the device's width:

.button {
    background-image: url("https://image.flaticon.com/icons/png/512/622/622669.png");
    background-repeat: no-repeat;
    background-position: right calc(50% + 40px) bottom 50%;
    background-size: 16px;
    padding: 10px 60px;
}
<input type="submit" value="Search" class="button">

I added the padding to make it look like your screenshot. However, it will also work with a full-width button and won't have a problem with responsiveness.

By changing 40px inside calc(50% + 40px) you can set it to the desired margin. I hope it's the solution you were looking for.

Amirhossein Shahbazi
  • 1,082
  • 1
  • 6
  • 13