Issue
I'm trying to horizontally and vertically center some radio buttons: http://jsfiddle.net/yxxd0cht/
I was thinking of using a flexbox or something like that, but I couldn't get it to work.
The 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;
}
The 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>
Solution
If you're open to using flexbox, and you're using HTML5 syntax, I assume your browser requirements would allow you to use another strategy as well. This is my favorite way of precisely centering an element of unknown dimensions inside a container of unknown dimensions.
Note that I cleaned up the markup as well--since you're not using any JavaScript that requires you to precisely identify items by their class or ID, the only ID that you really care about is that of the #green
div. The remaining elements can be easily addressed by using element-level selectors, which helps you avoid over-specifying styles and makes long-term maintenance easier.
#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>
Answered By - Palpatim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.