While trying to write semantic HTML, how can you lay out certain elements that usually require additional containers to place elements within others?
For instance, placing an icon within an input field. I’d prefer not to use a div or span for each instance unless necessary. Looking for everyone’s input on this! Thanks!
Maybe you can show a design so it’s easier to visualize what you’re trying to achieve. Adding an icon to your form inputs doesn’t make anything unsemantic. Wrap the input and the label elements in a div, and you can safely target the icon from CSS within that group. Make sure the icon has ‘aria-hidden=“true”’ so screen reader users don’t hear unnecessary descriptions like “search icon”.
These are problems that have been solved many times over the years. I’d check out well-established UI component libraries to see how they achieve both semantic and accessible designs.
@Lyle
This only works properly if you use phrasing content inside. With anything else, assistive technologies may start behaving weirdly, for example reading single fields as a group. I just recently fixed such a bug (we had a div inside a label).
@Lyle
It’s possible to nest the input inside the label, but using the ‘for’ attribute is recommended for better accessibility, layout, and styling options.
@Lyle
Thank you! You have just changed the way I code because I use a lot of Angular’s @for in dynamic forms, leading to pollution in labels and inputs interfacing with them.
I know that. I am wondering what people would do while trying to follow semantic recommendations in this situation where you’d want to overlay an icon over input.
Should I wrap the icon and input in a label or just use divs? If I use divs, are there aria attributes I should be using?
Heads-up though, be careful putting icons visually inside , especially on sign-in/signup forms. Browsers and password extensions often drop triggers in these fields, and you don’t want your icon conflicting with a user using their password manager.