gpt4 book ai didi

html - 居中单选按钮(flexbox?)

转载 作者:行者123 更新时间:2023-11-28 17:27:58 25 4
gpt4 key购买 nike

我正在尝试将一些单选按钮水平和垂直居中: 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>

最佳答案

如果您愿意使用 flexbox,并且您正在使用 HTML5 语法,我假设您的浏览器要求也允许您使用另一种策略。这是我最喜欢的将未知尺寸的元素精确居中在未知尺寸的容器中的方法。

请注意,我也清理了标记——因为您没有使用任何要求您通过类或 ID 精确识别元素的 JavaScript,您真正关心的唯一 ID 是 的 ID #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%);
}
<!-- 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>

关于html - 居中单选按钮(flexbox?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26757931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com