チェックボックス、ラヂオボタンをcssで装飾する際に隣接セレクタが使えない場合
前提 wordpressのcontactform7で作成したフォームで、テーマのベースはBootstrap4
<div class="form-group wpcf7-form-control wpcf7-checkbox siryo1"> <div class="checkbox wpcf7-form-control wpcf7-checkbox siryo1"> <label> <input name="siryo1" value="" aria-invalid="false" type="checkbox"> 会社案内 </label> </div> </div>
以下のページを参考にデザインを変更しようとする。
ただし、labelの子要素にinputがあって隣接セレクタが使えない・・・
ということでjqueryで親要素のlabelにクラスを追加して、labelの疑似要素のopacityを変化させました。
$iconColor: $green; input[type=radio], input[type=checkbox] { display: none; } .radio label, .checkbox label { box-sizing: border-box; -webkit-transition: background-color 0.2s linear; transition: background-color 0.2s linear; position: relative; display: inline-block; margin: 0 20px 8px 0; padding: 12px 12px 12px 42px; border-radius: 8px; background-color: #f6f7f8; vertical-align: middle; cursor: pointer; &:hover { background-color: #e2edd7; &:after { border-color: $iconColor; } } &:after { -webkit-transition: border-color 0.2s linear; transition: border-color 0.2s linear; position: absolute; top: 50%; left: 15px; display: block; margin-top: -10px; width: 16px; height: 16px; border: 2px solid #bbb; border-radius: 6px; content: ''; } } .radio label { &:before { -webkit-transition: opacity 0.2s linear; transition: opacity 0.2s linear; position: absolute; top: 50%; left: 20px; display: block; margin-top: -5px; width: 10px; height: 10px; border-radius: 50%; background-color: $iconColor; content: ''; opacity: 0; } &.checked:before { opacity: 1; } } .checkbox label { &:before { -webkit-transition: opacity 0.2s linear; transition: opacity 0.2s linear; position: absolute; top: 50%; left: 21px; display: block; margin-top: -7px; width: 5px; height: 9px; border-right: 3px solid $iconColor; border-bottom: 3px solid $iconColor; content: ''; opacity: 0; -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); transform: rotate(45deg); } &.checked:before { opacity: 1; } }
以下のページを参考にjqueryを書く。
$('input[type=checkbox] , input[type=radio]').change(function(){ if ($(this).is(':checked')) { $(this).parents('.checkbox').find('label').addClass('checked'); } else { $(this).parents('.checkbox').find('label').removeClass('checked'); } });