<分区>
<分区>
我有 2 个代表 +/- 符号的元素,当这两个元素可见时,它们代表 +
,单击时垂直元素消失,变成 -
。
+ 和 - 符号都在一个圆圈内,我想使该圆圈内的垂直和水平元素居中。
这是一个 fiddle :http://jsfiddle.net/9ek3gt7o/10
HTML:
<span class="plusminussign closed">
<div class="circle">
<div class="horizontal"></div>
<div class="vertical"></div>
</div> <!-- .circle -->
</span> <!-- .plusminussign -->
CSS:
.plusminussign{
position: relative;
display:inline-block;
height: 24px;
width: 24px;
vertical-align: bottom;
opacity: .7;
background: green;
border-radius: 50%;
color: #fff;
margin: 10px auto;
cursor: pointer;
}
.circle .horizontal {
position: absolute;
background-color: #fff;
width: 15px;
height: 2.5px;
left: 50%;
top: 50%;
}
.circle .vertical {
position: absolute;
background-color: #fff;
width: 2.5px;
height: 15px;
left: 50%;
top: 50%;
}
.closed .horizontal {
transition: all 0.5s ease-in-out;
transform: rotate(-90deg);
opacity: 1;
}
.closed .vertical {
transition: all 0.5s ease-in-out;
transform: rotate(-90deg);
}
.opened {
opacity: 1;
}
.opened .horizontal {
transition: all 0.5s ease-in-out;
transform: rotate(90deg);
opacity: 0;
}
.opened .vertical {
transition: all 0.5s ease-in-out;
transform: rotate(90deg);
}
单击时,opened
类将添加到容器 .plusminussign
中。
jQuery:
$('.plusminussign').on('click', function(){
$(this).toggleClass('opened');
});
我想要一个兼容 x-browser 的响应式解决方案,这样我就不会在屏幕变小时失去定位。
如何使圆内的水平和垂直元素居中?
最佳答案
要居中你有几个解决方案:
负边距
适用于旧版浏览器和新版浏览器,但您必须使用高度/宽度进行硬编码
.circle{
position: relative;
height: 100px;
width: 100%;
border-radius: 50%
}
.plus-vert{
height: 50px;
width: 2px;
background-color: #fff;
position: absolute;
top: 50%;
left: 50%;
margin: -25px 0 0 -1px;
}
.plus-horiz{
height: 2px;
width: 50px;
background-color: #fff;
position: absolute;
top: 50%;
left: 50%;
margin: -1px 0 0 -25px;
}
上/左值将您的线的左上角放在圆的中心。负边距在每次访问时将行向后移动一半,使元素居中。这适用于较旧的浏览器,但不太理想,因为您必须对高度/宽度进行硬编码。
CSS3 转换
这与之前的方法基本相似,不同之处在于您使用变换将其向后移动一半而不是负边距。
.circle{
position: relative;
height: 100px;
width: 100%;
border-radius: 50%
}
.plus-vert{
height: 50px;
width: 2px;
background-color: #fff;
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
.plus-horiz{
height: 2px;
width: 50px;
background-color: #fff;
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
这只与启用 CSS3 的浏览器兼容,并且具有不关心高度/宽度的好处,因为它在 % 中。
flex 盒子
这使用了 flex box布局居中
.圆圈{ 显示: flex ; 证明内容:居中; 对齐元素:居中; 高度:100px; 宽度:100%; 边界半径:50%
.plus-vert{
height: 50px;
width: 2px;
background-color: #fff;
}
.plus-horiz{
height: 2px;
width: 50px;
background-color: #fff;
}
这样做的好处是可以从子项中获取所有布局逻辑并将其放在父项中。
应该都不错,就看你想支持什么浏览器了。
关于jquery - 在圆圈内居中加/减切换元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52012913/