Search code examples
inputlabelaccessibilitybem

BEM. How to deal with label for/id?


As far as I know, BEM does not use elements id at all. But how to deal in this case with the label for/id combined with inputs? If I do not use id, people who're using screen readers will not get that this label is for that input. Am I right?


Solution

  • BEM suggests avoiding id for css selectors. It's perfectly valid to use id for A11y and usability.

    <form class="form" method="post" action="">
        <label for="email" class="form__label">Email</label>
        <input type="email" id="email" class="form__control"/>
    </form>
    

    In the example above we are styling the input as an Element of the form block with the form__control class.

    Also you can not use aria attributes without id for pointers to descriptive elements.

    <div role="application" aria-labelledby="calendar" aria-describedby="info">
        <h1 id="calendar">Calendar</h1>
        <p id="info">
            This calendar shows the game schedule for the Boston Red Sox.
        </p>
        <div role="grid">
            ...
        </div>
    </div>
    

    Example taken from: https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-describedby_attribute