Search code examples
htmlcssbem

How to make a general input field class


I am experimenting with BEM (CSS) and I am wondering how to make a class for styling all text fields background color and border (I am not using a CSS preprocessor yet).

For example, I have a text field inside my search field and also inside a contact form (and at 5 other places). Then I don't want to style the same background color and border in both cases, I want an .input class for all fields.

Can add the .input class on both elements like this:

<!-- Searchbox -->
<div class="searchbox">
   <input type="text" class="searchbox__field input">
   <button class="searchbox__button>Search!</button>
</div>

<!-- Contact form-->
<form class="contact-form">
   <div class="contact-form__control">
      <label class="contact-form__label">Name:</label>
      <input class="contact-form__field input">
   </div>
</form>

<!-- .input styling for all fields -->
<style>

   .input {
      border: 1px solid green;
      background-color: #dbdbdb;
      border-radius: 5px;
   }

</style>

Solution

  • Can add the .input class on both elements like this

    Yes, you can:

    <input type="text" class="searchbox__field input">
    

    Here you have a mix: the same DOM node is both an element (.searchbox__field) and a block (.input).

    See also: the official documentation.