具有转换问题的绝对位置居中
absolute position centering with transform having issues
我有一些列表项需要居中。我必须使用绝对位置来完成它,因为它与另一个 div 重叠。我可以使用位置和转换属性来做到这一点。但是当设备宽度较小时会出现问题。我希望它尽可能长地居中,但它在设备宽度足够小之前就中断了。我可以使用 calc 修复它,但是当 ul 宽度未知时怎么办?
codepen
.parent {
height: 70px;
margin-top: 100px;
width: 100%;
background: #000;
position: relative;
}
ul,li {
list-style-type: none;
}
ul {
position: absolute;
bottom: 0;
margin: 0;
padding: 0;
top: 0;
left: 50%;
transform: translate(-50% , 0);
clear:both;
display:block;
}
li {
height: 70px;
width: 70px;
background: #f44;
display: inline-block;
border-radius: 50%;
margin-left: 10px;
margin-right: 10px;
margin-top: 0;
margin-bottom: 0;
}
<div class="parent">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
为什么不直接将 text-align: center
添加到 ul
标签,根本不进行转换或定位。
如果 li
是行内块,它将居中并在 ul
边界处换行。
像这样更新您的 ul
规则,其中 left: 0
/right: 0
将使它成为全宽,text-align
使 li
居中
ul {
position: absolute;
top: 0;
left: 0;
right: 0;
padding: 0;
margin: 0;
text-align: center
}
示例片段
.parent {
height: 70px;
margin-top: 100px;
width: 100%;
background: #000;
position: relative;
}
ul,li {
list-style-type: none;
}
ul {
position: absolute;
top: 0;
left: 0;
right: 0;
padding: 0;
margin: 0;
text-align: center
}
li {
height: 70px;
width: 70px;
background: #f44;
display: inline-block;
border-radius: 50%;
margin-left: 10px;
margin-right: 10px;
margin-top: 0;
margin-bottom: 0;
}
<div class="parent">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
我有一些列表项需要居中。我必须使用绝对位置来完成它,因为它与另一个 div 重叠。我可以使用位置和转换属性来做到这一点。但是当设备宽度较小时会出现问题。我希望它尽可能长地居中,但它在设备宽度足够小之前就中断了。我可以使用 calc 修复它,但是当 ul 宽度未知时怎么办?
codepen
.parent {
height: 70px;
margin-top: 100px;
width: 100%;
background: #000;
position: relative;
}
ul,li {
list-style-type: none;
}
ul {
position: absolute;
bottom: 0;
margin: 0;
padding: 0;
top: 0;
left: 50%;
transform: translate(-50% , 0);
clear:both;
display:block;
}
li {
height: 70px;
width: 70px;
background: #f44;
display: inline-block;
border-radius: 50%;
margin-left: 10px;
margin-right: 10px;
margin-top: 0;
margin-bottom: 0;
}
<div class="parent">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
为什么不直接将 text-align: center
添加到 ul
标签,根本不进行转换或定位。
如果 li
是行内块,它将居中并在 ul
边界处换行。
像这样更新您的 ul
规则,其中 left: 0
/right: 0
将使它成为全宽,text-align
使 li
居中
ul {
position: absolute;
top: 0;
left: 0;
right: 0;
padding: 0;
margin: 0;
text-align: center
}
示例片段
.parent {
height: 70px;
margin-top: 100px;
width: 100%;
background: #000;
position: relative;
}
ul,li {
list-style-type: none;
}
ul {
position: absolute;
top: 0;
left: 0;
right: 0;
padding: 0;
margin: 0;
text-align: center
}
li {
height: 70px;
width: 70px;
background: #f44;
display: inline-block;
border-radius: 50%;
margin-left: 10px;
margin-right: 10px;
margin-top: 0;
margin-bottom: 0;
}
<div class="parent">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>