Search code examples
htmlcssline-breaks

How can i avoid line break after radiobutton, make going it to a new line only with it's label, not separately


I have a code like this:

<div class="days" style="width:300px;">
<input id="monday" type="radio" name="monday" value="1">
<label for="monday"> monday</label>
<input id="tuesday" type="radio" name="tuesday" value="2">
<label for="tuesday"> tuesday</label>
<input id="wednesday" type="radio" name="wednesday" value="3">
<label for="wednesday"> wednesday</label>
<input id="thursday" type="radio" name="thursday" value="4">
<label for="thursday"> thursday</label>
</div>

And here is jsfiddle - https://jsfiddle.net/k96x02qL/

So as you see, for some values of width of the main div, sometimes there is a situation, when label is on a new line, but radiobutton is not (picture one):

picture one

So i want to see something like this (with any value of width of main div) (picture two):

picture two

How can i implement it? For some reason i can't wrap input and it's label in one more div. Only can add some styles using "name" html attribute or something like this...


Solution

  • You can do this without changing the HTML by not showing the input button (opacity: 0) and putting a 'pretend' button in a pseudo element before each label.

    This snippet uses a couple of Unicode circles to do this but of course you may want to do it another way - e.g. a background radio gradient or an image.

    This way the label as a whole goes across whole if there isn't room for it at the end of a line.

    input {
      opacity: 0;
      position: absolute;
      left: 50px
    }
    
    input:checked+label::before {
      content: '\26ab';
    }
    
    label {
      position: relative;
    }
    
    label::before {
      content: '\26aa';
      margin-right: 5px;
      position: relative;
    }
    <div class="days" style="width:300px;">
      <input id="monday" type="radio" name="monday" value="1">
      <label for="monday"> monday</label>
      <input id="tuesday" type="radio" name="tuesday" value="2">
      <label for="tuesday"> tuesday</label>
      <input id="wednesday" type="radio" name="wednesday" value="3">
      <label for="wednesday"> wednesday</label>
      <input id="thursday" type="radio" name="thursday" value="4">
      <label for="thursday"> thursday</label>
    </div>