This article is reproduced from: Desert Blog
Horizontal direction (unknown width)
Take the paging component as an example
html
<div class="pagination">
<ul>
<li><a href="#">Prev</a></li>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li><a href="#">Next</a></li>
</ul>
</di>
css
ul{
padding: 0;
}
.pagination li {
line-height: 25px;
list-style: none;
}
.pagination a {
display: block;
color: #f2f2f2;
text-shadow: 1px 0 0 #101011;
padding: 0 10px;
border-radius: 2px;
box-shadow: 0 1px 0 #5a5b5c inset, 0 1px 0 #080808;
background: linear-gradient(#434345, #2f3032);
}
.pagination a:hover {
text-decoration: none;
box-shadow: 0 1px 0 #f9bd71 inset, 0 1px 0 #0a0a0a;
background: linear-gradient(#f48b03, #c87100);
}
1. Given a width, use margin: auto
2. 利用 display: inline-block;
.pagination{
text-align: center;
font-size: 0; //解决子元素为inline-block时两边多余的空白
}
ul{
padding: 0;
}
.pagination li {
display: inline-block;
line-height: 25px;
list-style: none;
zoom: 1;
margin: 0 5px;
}
.pagination a {
text-decoration: none;
display: block;
color: #f2f2f2;
text-shadow: 1px 0 0 #101011;
padding: 0 10px;
border-radius: 2px;
box-shadow: 0 1px 0 #5a5b5c inset, 0 1px 0 #080808;
background: linear-gradient(#434345, #2f3032);
}
.pagination a:hover {
box-shadow: 0 1px 0 #f9bd71 inset, 0 1px 0 #0a0a0a;
background: linear-gradient(#f48b03, #c87100);
}
Advantages : Strong scalability.
Disadvantage : Can cause extra white space between elements. 解决方法
: Set the parent element fong-size: 0
and resize the child element
3. The method of floating to achieve horizontal centering
- First: the entire container
左浮动
.pagination{
float: left;
width: 100%;
overflow: hidden;
position: relative; //让子元素以他为移动
}
ul
Then: move right on the list item50%(left:50%;)
.pagination ul{
padding: 0;
clear: left;
float: left; // 让内容由内部元素大小撑起来
position: relative;
left: 50%;
}
- Finally: we
li
also defineposition:relative
the attribute on the above, but the direction of its movement and the direction of the listul
movement are just the opposite direction, and the value of its movement remains the same
Disadvantage : The implementation principle is more complicated.
4. Absolute positioning to achieve horizontal centering
Common cases of knowing the width:
.ele { position: absolute; width: 宽度值; left: 50%; margin-left: -(宽度值/2); }
don't know the width
.pagination {
position: relative;
height: 40px; /*最好设置高度,不然是沒有高度*/
}
.pagination ul {
padding: 0;
margin: 0;
position: absolute;
left: 50%;
}
.pagination li {
line-height: 25px;
margin: 0 5px;
float: left;
position: relative;/*注意,这里不能是absolute,大家懂的*/
right: 50%;
}
5. Flex implements the horizontal centering method
.pagination{
display: flex;
justify-content: center;
}
6. CSS3 fit-content to achieve horizontal centering method
.pagination ul{
width: -moz-fit-content;
width: -webkit-fit-content;
width: fit-content;
margin: auto;
}
Disadvantage: Compatibility is not good enough