我有一个div,在其中有一个按钮:
我将按钮位置设置为absolute
,其样式代码如下:
.buy-btn {
text-align: center;
position: absolute;
bottom: 10px;
}
如何让它居中对齐?我尝试添加margin: 0 auto;
,但不起作用。
我有一个div,在其中有一个按钮:
我将按钮位置设置为absolute
,其样式代码如下:
.buy-btn {
text-align: center;
position: absolute;
bottom: 10px;
}
如何让它居中对齐?我尝试添加margin: 0 auto;
,但不起作用。
如果我理解你的问题,则它将按以下方式工作。
你可以用三种方法实现它。
No1 - 使用position。将按钮父级div的宽度应用为100%,并将按钮样式应用为以下内容。
.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%,并从按钮中删除position属性的absolute。
.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 */
}
第三步 - 使用margin,将宽度100%应用于您的父div,并从按钮中删除absolute定位。
.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%);
}
如果你想使用位置,那么在这种情况下你需要给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;
}
这里有一个使用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>
看看这个答案,我认为这会对你有所帮助。 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">