我制作了一个按钮,将其放在div中,使div和按钮居中对齐,但是按钮从其最左侧对齐,使其偏离中心。有没有办法使它从实际中心居中对齐?
.btndiv{
width: 80%;
height: 500px;
margin: 0 auto;
text-align: center;
}
.testbutton{
position: absolute;
bottom: 0px;
width: 30%;
height: 50px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style3.css">
</head>
<body>
<div class="btndiv">
<button class=" testbutton"> A button </button>
</div>
</body>
</html>
答案 0 :(得分:1)
您可以使用flexbox做到这一点:
这是更新的代码段:
.btndiv {
width: 80%;
height: 500px;
margin: 0 auto;
text-align: center;
display: flex;
align-items: center;
}
.testbutton {
width: 30%;
height: 50px;
margin: 0 auto;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style3.css">
</head>
<body>
<div class="btndiv">
<button class=" testbutton"> A button </button>
</div>
</body>
</html>
答案 1 :(得分:1)
定义其在left:50%;
中的位置,即。到中心,然后将transform:translateX(50%);
添加到元素,以便它会切掉不需要的空间,从而使该项目自动与中心对齐。
.btndiv{
width: 80%;
height: 500px;
margin: 0 auto;
text-align: center;
}
.testbutton{
position: absolute;
bottom: 0px;
width: 30%;
height: 50px;
left:50%;
transform: translateX(-50%);
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style3.css">
</head>
<body>
<div class="btndiv">
<button class=" testbutton"> A button </button>
</div>
</body>
</html>
答案 2 :(得分:1)
对于对齐元素,始终建议使用“网格”,如代码段所示:
.grid-container {
display: grid;
grid-template-columns: auto auto auto;
}
.grid-item {
background-color: rgba(255, 255, 255, 0.3);
border: 1px solid rgba(0, 0, 0, 0.1);
padding: 10px;
font-size: 10px;
text-align: center;
}
<html>
<body>
<div class="grid-container">
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"><button class=" testbutton"> A Button </button>
</div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
</div>
</body>
</html>
答案 3 :(得分:0)
在css下方添加,就可以完成...
.testbutton {
left: 0;
right: 0;
margin: auto;
}
此外,如果要居中对齐,请在CSS下方添加
.testbutton {
left: 0;
right: 0;
top:0;
bottom:0;
margin: auto;
}
.btndiv{
width: 80%;
height: 500px;
margin: 0 auto;
text-align: center;
}
.testbutton {
left: 0;
right: 0;
margin: auto;
}
.testbutton{
position: absolute;
bottom: 0px;
width: 30%;
height: 50px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style3.css">
</head>
<body>
<div class="btndiv">
<button class=" testbutton"> A button </button>
</div>
</body>
</html>