对中单选按钮(flexbox?)

时间:2014-11-05 13:03:52

标签: html css radio

我试图水平和垂直居中一些单选按钮: http://jsfiddle.net/yxxd0cht/

我在考虑使用flexbox或类似的东西,但我无法让它工作。

CSS:

.costs
{
font-family: Arial, sans-serif;
background-color:#FFBC02;
color:white;
padding: 5px 12px;
margin-left:5px;
font-size: 1.05em;
}

input[type=radio]
{
display:none;
}

HTML:

<div id="green">
<fieldset id="costs">
                <legend>Costs: </legend>
                <input id="free" name="costs" type="radio" value="free">
                <label class="costs" for="free">Free</label>

                <input id="chargeable" name="costs" type="radio" value="chargeable">
                <label class="costs" for="chargeable">Chargeable</label>

                <input id="mixed" name="costs" type="radio" value="mixed" checked>
                <label  class="costs" for="mixed">Mixed</label>
                </fieldset>
</div>

1 个答案:

答案 0 :(得分:1)

如果您愿意使用flexbox,并且您使用的是HTML5语法,我认为您的浏览器要求也允许您使用其他策略。这是我最喜欢的方法,即将未知尺寸的元素精确定位在未知尺寸的容器中。

请注意,我也清理了标记 - 因为您没有使用任何需要您按类或ID精确识别项目的JavaScript,您真正关心的唯一ID是{{1 div。通过使用元素级选择器可以轻松解决其余元素,这有助于避免过度指定样式并使长期维护更容易。

#green
#green {
  background-color: green;
  height: 200px;
  /* Make this the positioning parent for fieldset */
  position: relative;
}
#green label {
  font-family: Arial, sans-serif;
  background-color: #FFBC02;
  color: white;
  padding: 5px 12px;
  margin-left: 5px;
  font-size: 1.05em;
}
#green input[type=radio] {
  display: none;
}
#green input[type=radio]:checked + label {
  background-color: lightgreen;
}
#green fieldset {
  /* Border added for visualization */
  border: 1px solid red;
  /* Position absolute will position relative to first
  non-static ancestor (in this case, #green) */
  position: absolute;
  /* Positions fieldset's top/left corner exactly in the
  center of #green */
  top: 50%;
  left: 50%;
  /* Translate's percentages are based on dimensions of 
  the element, not the width of the container, like 
  CSS % units. */
  transform: translate(-50%, -50%);
}