【发布时间】:2018-09-09 02:52:14
【问题描述】:
我有一个 div,里面有一个按钮:
我让按钮位置为absolute,其样式代码:
.buy-btn {
text-align: center;
position: absolute;
bottom: 10px;
}
如何将其对齐到中心?我尝试添加margin: 0 auto;,但它不起作用。
【问题讨论】:
标签: html css css-position
我有一个 div,里面有一个按钮:
我让按钮位置为absolute,其样式代码:
.buy-btn {
text-align: center;
position: absolute;
bottom: 10px;
}
如何将其对齐到中心?我尝试添加margin: 0 auto;,但它不起作用。
【问题讨论】:
标签: html css css-position
如果我理解了你的问题,那么它将按如下方式工作。
您可以通过三种方式做到这一点。
No1 - 使用位置。将宽度 100% 应用到按钮父 div 并应用按钮样式如下。
.buy-btn{
display: inline-block; /* Display inline block */
text-align: center; /* For button text center */
position: absolute; /* Position absolute */
left: 50%; /* Move 50% from left */
bottom: 10px; /* Move 10px from bottom */
transform: translateX(-50%); /* Move button Center position */
}
No2 - 使用父 div,将宽度 100% 应用到您的父 div 并从按钮中删除绝对位置。
.parentDiv {
width: 100%; /* for full width */
text-align: center; /* for child element center */
}
.buy-btn{
display: inline-block; /* Display inline block */
text-align: center; /* For button text center */
}
No3 - 使用边距,将宽度 100% 应用于您的父 div 并从按钮中删除绝对位置。
.parentDiv {
width: 100%; /* for full width */
}
.buy-btn{
display: inline-block; /* Display inline block */
text-align: center; /* For button text center */
margin: 0 auto; /* For button center */
}
【讨论】:
/* Replace below css and add position relative to its parent class*/
.buy-btn {
text-align: center;
position: absolute;
bottom: 10px;
left: 50%;
display: inline-block;
transform: translateX(-50%);
}
【讨论】:
您可以添加这些。
.buy-btn {
/* ... */
left:50%;
transform: translateX(-50%);
}
【讨论】:
这是一个使用 flexbox 的解决方案,希望你能从中学到一些东西。
.container{
display: flex;
height: 200px;
width: 500px;
background-color: powderblue;
justify-content: center;
}
button{
height: 20px;
align-self: center;
}
<div class="container">
<button>click me</button>
</div>
【讨论】:
您需要将margin-left: auto; margin-right: auto; 与position:absolute 一起使用,如下所示:-
.btn-box{ position: relative; }
.btn-center {
position: absolute;
top: 10px;
left: 0px;
right: 0px;
margin-left: auto;
margin-right: auto;
width:100px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<a href="#" class="btn btn-warning btn-center">Click here</a>
【讨论】:
如果你想使用 position ,在这种情况下你需要给 btn 宽度,然后它才能工作
.buy-btn {
text-align: center;
position: absolute;
width:100px;
left:50%;
margin-left:-50px; /* please change it according to the width; always the half of width */
bottom: 10px;
}
【讨论】:
检查这个答案,我认为这会对你有所帮助。 https://codepen.io/anon/pen/ZoYvME
.buy-btn {
/* ... */
position:absolute;
margin-left:50%;
margin-right:50%;
transform: translateX(-50%);
bottom: 10px;
}
<input type="button" class="buy-btn" value="hai">
【讨论】: