演示
https://codepen.io/anon/pen/yqwJWE
我做了一个自定义单选按钮,但 DOM 结构使得自定义复选框的中间对齐变得困难,我需要具有不同行的标签位于右侧并且复选框水平居中。
<div>
<input id="radio-1" class="radio-custom" name="radio-group" type="radio" checked>
<label for="radio-1" class="radio-custom-label"><p>Row one</p><p>Row two</p> </label>
</div>
最佳答案
您可以使用 CSS Grid 轻松做到这一点
将网格声明为 2 行 2 列(将第一列设置为最小内容),对齐元素居中,并使您的 :before 元素跨越 2 行
/* only demo styles */
body {
font-family: Raleway;
}
.wrap{
/*prevents from occupying 100% width*/
display:inline-block;
}
/* end only demo styles */
.checkbox-custom, .radio-custom {
opacity: 0;
position: absolute;
}
.checkbox-custom, .checkbox-custom-label, .radio-custom, .radio-custom-label {
display: grid;
align-items:center;
grid-template-columns: min-content 1fr;
grid-template-rows: 1fr 1fr;
margin: 5px;
cursor: pointer;
}
.checkbox-custom-label p, .radio-custom-label p{
margin:0;
}
.checkbox-custom + .checkbox-custom-label:before, .radio-custom + .radio-custom-label:before {
content: '';
/*tells the button to occupy both rows */
grid-row: 1 / 3;
background: #fff;
border: 2px solid #ddd;
width: 20px;
height: 20px;
padding: 2px;
margin-right: 10px;
text-align: center;
}
.checkbox-custom:checked + .checkbox-custom-label:before {
background: rebeccapurple;
box-shadow: inset 0px 0px 0px 4px #fff;
}
.radio-custom + .radio-custom-label:before {
border-radius: 50%;
}
.radio-custom:checked + .radio-custom-label:before {
background: #ccc;
box-shadow: inset 0px 0px 0px 4px #fff;
}
.checkbox-custom:focus + .checkbox-custom-label, .radio-custom:focus + .radio-custom-label {
outline: 1px solid #ddd; /* focus style */
}
<form>
<div class='wrap'>
<input id="radio-1" class="radio-custom" name="radio-group" type="radio" checked>
<label for="radio-1" class="radio-custom-label"><p>Row one</p><p>Row two</p> </label>
</div>
</form>
关于html - 在自定义单选按钮上对齐元素中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51814296/