我正在尝试制作一个按钮,当用户点击它时会展开一个文本标签。它工作正常,但是我有两个问题:
- 我无法让按钮中的文本完美居中。很奇怪,当我将
line-height
降低到 0% 时,文本实际上下降了。 - 由于某种原因,按钮在移动设备上被拉长了(on mobile 对比 on computer)
代码如下(请见谅,我是HTML n00b)
function myFunction() {
var x = document.getElementById('myDIV');
var y = document.getElementById('myDIV2');
var elem = document.getElementById("btn");
if (x.style.opacity == 1) {
x.style.opacity = 0;
y.style.opacity = 0
elem.innerHTML = "+";
} else {
x.style.opacity = 1;
y.style.opacity = 1;
elem.innerHTML = "-";
}
}
@-webkit-keyframes pulsate
{
0% {border-color: #fff;}
50% {border-color: #FF6B35;}
100% {border-color: #fff;}
}
body {
background-color: black;
}
.myDIV {
width: 100%;
padding: 20px 0;
text-align: center;
background-color: white;
color: black;
opacity: 0;
font-family: "Verdana";
}
.btn {
font-size: 200%;
display:block;
height: 50px;
width: 50px;
border-radius: 50%;
border: 2px white solid;
color: white;
background-color: transparent;
margin: 0 auto;
line-height: 10%;
animation: pulsate 2s infinite;
outline: none;
font-family: "Verdana";
}
.vertical-line{
width: 0px; /* Use only border style */
height: 100%;
border: 1px solid white; /* This is default border style for <hr> tag */
margin: 0 auto;
opacity: 0;
}
<body>
<div class="myDIV" id="myDIV">This is my DIV element.</div>
<div class="vertical-line" id="myDIV2" style="height: 90px;"></div>
<button class="btn" id="btn" onclick="myFunction()">+</button>
</body>
最佳答案
你可以使用flex-box
。使垂直和水平对齐元素更容易。查看 https://css-tricks.com/snippets/css/a-guide-to-flexbox/获取简单指南。
在您的 .btn
CSS 选择器上,更改/添加以下属性和值:
font-size: 200%;
display: block;
height: 50px;
width: 50px;
border-radius: 50%;
border: 2px white solid;
color: white;
background-color: transparent;
margin: 0 auto;
line-height: 0%;
animation: pulsate 2s infinite;
outline: none;
font-family: "Verdana";
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
align-items: center;
justify-content: center;
为了防止拉伸(stretch),添加一个max-width
属性和值
max-width: 50px;
这应该可以解决这两个错误。
关于javascript - 按钮在手机上拉伸(stretch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44281095/