<分区>
<分区>
CSS 专家!首先,如果这似乎是重复的,我深表歉意!
我有一组带有文本的按钮,我想将它们水平排列。出于这个原因,我将 div
与 display: "flex"
一起使用,将它们作为其子项包含起来。每个按钮都有如下基本布局:
<div>
<div style={normalStyle}>
<div style={lineStyle}/>
<div style={circleStyle}>
<div style={onButtonStyle}/>
</div>
</div>
{children}
</div>
我使用的样式的最小化版本如下:
{
normalStyle: {
position: "relative",
cursor: "pointer",
},
lineStyle: {
position: "absolute",
left: 0,
top: "10px",
height: "15px",
width: "38px",
},
circleStyle: {
position: "absolute",
left: 0,
top: 7,
height: "20px",
width: "20px",
},
onButtonStyle: {
position: "absolute",
left: 0,
top: 0,
height: "20px",
width: "20px",
}
}
目标是实现某种 Material 按钮,其中我有一个 slider (使用 lineStyle
)和一个基圆(使用 circleStyle
)和一个覆盖按钮圆(使用 onButtonStyle
)根据按钮的选中状态展开或缩小(为简单起见,此处未显示 transition
样式)。
看起来文本 (children
) 不尊重按钮,因此它们重叠,我怀疑这与 absolute
定位有关.此外,当我想水平放置多个这些按钮时,它们看起来像这样:
文本显然是水平对齐的(如预期的那样),但按钮再次以 absolute
方式 w.r.t. 定位。子文本。
<div style={{ display: "flex" }}>
<Button>A toggle button</Button>
<Button>A toggle button</Button>
我四处搜索并坦率地找到了很多解决方案,但到目前为止我严重未能使它正常工作。如果有人能对此有所了解,我将不胜感激。提前致谢!
最佳答案
我不太确定我理解你的问题.. 我为您整理了代码并对其进行了清理 + 为清晰起见,将其转换为简单的 HTML 和 CSS。
首先 .toggleStyle
需要一个明确的大小,因为子级都是绝对定位的,父级在技术上是不可见的。这就是文本与你的 div 重叠的原因。
我使用 flexbox 使元素彼此相邻。如果愿意,您可以考虑使用固定宽度的 div 和 float 。
最后,你的 onButtonStyle
不应该是绝对定位的,因为这样做对于它在嵌套中找到的第一个相对父级来说是绝对的,并且不会位于它的父级中。
<div class="container">
<div class="toggleStyle">
<div class="lineStyle"></div>
<div class="circleStyle">
<div class="onButtonStyle"></div>
</div>
</div>
<!-- this is where you will add you {children} -->
<label class="textStyle">Button Text</label>
</div>
和CSS
.container {
display: flex;
margin: 10px;
}
.toggleStyle {
position: relative;
cursor: pointer;
width: 40px;
height: 20px;
}
.lineStyle {
position: absolute;
left: 0;
top: 5px;
height: 10px;
width: 40px;
border-radius: 20px;
background-color: red;
}
.circleStyle {
position: absolute;
display: flex;
justify-content: center;
align-items: center;
left: 0;
height: 20px;
width: 20px;
border-radius: 50%;
background-color: blue;
}
.onButtonStyle {
height: 10px;
width: 10px;
border-radius: 50%;
background-color: yellow;
}
.textStyle {
line-height: 20px;
margin: 0 5px;
font-weight: bold;
}
我做了这个Pen给你。
我希望一切都清楚!
关于html - 将 DIV 与绝对定位的子项水平对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47235142/
相关文章:
html - CSS:在 <li> 和 <a> 标签之间的伪元素之前
javascript - 如何让一个简单的 <audio> 元素在滚动时停留在浏览器窗口的底部?
javascript - 与助焊剂 react : is this the dogmatic pattern or are there equal/better options?
javascript - 如何计算 localStorage 中的特定 ID?
javascript - 如何将自定义管道应用于 ngFor 迭代元素
javascript - 单击按钮时转到 Accordion 选项卡 Vanilla JavaScript