2014-11-05 27 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