2014-11-05 28 views
1

我试图水平和垂直居中一些单选按钮: http://jsfiddle.net/yxxd0cht/定心单选按钮(?Flexbox的)

我想用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> 
+0

任何人的想法? – Bosiwow 2014-11-05 15:43:58

回答

1

如果你打开使用Flexbox的,和你使用HTML5语法,我想你的浏览器的要求将允许你使用另一种策略。这是我最喜欢的方式,将未知尺寸的元素精确对中未知尺寸的容器。

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

#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%); 
 
}
<!-- Removed unnecessary classes & IDs throughout. 
 
The elements are easily addressible in CSS styles using 
 
#green as the parent. --> 
 
<div id="green"> 
 
    <fieldset> 
 
    <legend>Costs:</legend> 
 
    <input id="free" name="costs" type="radio" value="free"> 
 
    <label for="free">Free</label> 
 

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

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

+0

非常感谢! ;) – Bosiwow 2014-11-05 15:58:29