html - 在自定义单选按钮上对齐元素中心

标签 html css

演示

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/

相关文章:

jquery - 使用 html2canvas 更改背景无法正常工作

javascript - 将节点从不同数组移动到一个数组,然后再次将其移动到angularjs中的父数组

html - CSS获取元素的第一个子元素以显示为 block

javascript - Jquery 复选框分组 - 当至少单击一个子复选框时取消选中父级,当选中所有子复选框时选中父级

javascript - Kendo Core - 需要基本帮助

javascript - 使用jquery从html中删除表格行

javascript - 点击交换两个元素

php - 在更改和页面加载时执行 jQuery 函数?

html - CSS 高度 100% 两列

html - IE 与表单 css 样式不兼容