Semantic HTML Containers

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.

Label wrapping the input element.

Wren said:
Label wrapping the input element.

[deleted]

@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.

Rin said:

Wren said:
Label wrapping the input element.

[deleted]

Look it up, goober.

Input does not allow child elements.

Zara said:
Input does not allow child elements.

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?

@Dru
Just add the icon as a background and provide padding in the input, so that if the browser adds its own icons, there would be no clash.

What kind of semantic has an image to a search engine?
Zero if there is already a label.

is fine for this.
is intentionally semantically meaningless.

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.

Sometimes you have to add additional tags, and sometimes those tags are just vanilla div/span, but try to add as few as possible.

For ‘icon in an input’ - look into using a background image, non-repeating, positioned to the left side.