Thursday, April 30, 2020

Don't use label display block for radio and checkbox

<div class="form-group">
  <label id="recommend-label" class="label">Would you recommend freeCodeCamp to a friend?</label>
  
    <label><input type="radio" name="recommend" value="definitely">Definitely the greatest tutorial on earth</label>
  
  
    <label><input type="radio" name="recommend" value="maybe">Maybe</label>
  
  
    <label><input type="radio" name="recommend" value="not-sure">Not sure</label>
</div>

<style>
.form-group label:not(.label) {
  display: block;
  background: lightgreen;
  margin: 2px;  
}
</style>


The problem with label display block approach is that it makes the trailing spaces after the label clickable too.



Demo: https://jsfiddle.net/qadxjghy/


To make the label's trailing spaces not clickable, enclosed the label in div. And then change the input's enclosing label display to inline-flex

<div class="form-group">
  <label id="recommend-label" class="label">Would you recommend freeCodeCamp to a friend?</label>
  
    <div>
      <label><input type="radio" name="recommend" value="definitely">Definitely the greatest tutorial on earth</label>
    </div>
  
    <div>
      <label><input type="radio" name="recommend" value="maybe">Maybe</label>
    </div>
  
    <div>
      <label><input type="radio" name="recommend" value="not-sure">Not sure</label>
    </div>

</div>

.form-group label:not(.label) {
  display: inline-flex;
  background: lightgreen;
  margin: 2px;  
}

Output:



Demo: https://jsfiddle.net/qadxjghy/1/


display: inline-block can be used as well:



inline-flex is better, so we can use align-items: baseline to align the baseline of text to the baseline of the radio/checkbox buttons:



display attribute can be removed as well, but you can't set things like margin:



No comments:

Post a Comment