やりたかったこと
- ラジオボタンの見た目をかっこよくしたい(ザックリ)
- inputのtype属性はradioのままで実現したい
- CSSの編集は最低限にとどめたい
やったこと
- Bootstrap 4の
Button plugin
を適用
詳細
Bootstrap 4の導入
RailsにBootstrap 4を導入する手順については下記の投稿で解説してます。
Railsアプリで Bootstrap 4 を利用する - Qiita
Button pluginの適用
Bootstrap 4の公式ドキュメントにチェックボックスやラジオボタンの見た目をボタンにするサンプルが掲載されていたので、こちらを参考に実装しました。
Button plugin / Checkbox and radio buttons
Before
formのラジオボタン部分を抜粋
<div class="form-group row">
<div class="col-sm-2">
<%= f.label :sex, '性別', {class: 'form-label'} %>
</div>
<div class="col-sm-10">
<%= f.radio_button :sex, 0, {checked: true} %> 男性
<%= f.radio_button :sex, 1, {} %> 女性
</div>
</div>
After
formのラジオボタン部分を抜粋
<div class="form-group row">
<div class="col-sm-2">
<%= f.label :sex, '性別', {class: 'form-label'} %>
</div>
<div class="col-sm-10 btn-group" data-toggle="buttons">
<label class="btn btn-outline-secondary active" style="width:50%">
<%= f.radio_button :sex, 0, {checked: true} %> 男性
</label>
<label class="btn btn-outline-secondary" style="width:50%">
<%= f.radio_button :sex, 1, {} %> 女性
</label>
</div>
</div>