Having icons inside an input control is a very common behaviour. Classic use cases of search control with magnifier icon or password control with eye-icon (reveal/show password) or currency control with leading/trailing symbols or texts like dollar/pounds/INR are pretty common use cases. Most of these designs are achieved through any of the below approaches:
- Using positions (relative position parent, absolute position prefix/suffix).
- Using negative margins for suffix/prefix
- Directly squeezing in the prefix/suffix/text input in a wrapper element and removing the default border for text input and handling border/focus states through the wrapper element.
Now except with approach #3, we have one common problem with approach #1 and approach #2, "How do we make sure text inside input is not spilt over to prefix/suffix?". Oh that's simple, give padding (left/right) to the text input. Nope, in most cases, this is as straight forward as you thought but what if my prefix/suffix are dynamic values, beforehand I am not sure what sort of symbol or text I get, this info we get only during runtime.
For such issues, we have "ch" units to our rescue. Please find the below code pen snippet describing the approach #1 and #3 and elaborating on props & cons with them.
Code pen link: https://codepen.io/Raghavan/pen/Exybjev
Please comment below if you think of any downsides with this approach of using ch units and do follow me here for more updates or notifications related to CSS primarily and sometimes with React :)
Top comments (0)