小结——居中问题的解决

居中问题:

1.Fixed定位margin:0 auto;不管用,水平居中需要做如下处理:
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
2.relative定位margin:0 auto;管用,水平居中需要做如下处理:
position: relative;
display: flex;
flex-direction: column;
margin: 0 auto;
3.absolute定位 加margin 元素已知宽度

父元素设置为:position: relative;
子元素设置为:position: absolute;
距上50%,据左50%,然后减去元素自身宽度的距离就可以实现

<div class="box">
    <div class="content">
    </div>
</div>

.box {
    background-color: #FF8C00;
     300px;
    height: 300px;
    position: relative;
}
.content {
    background-color: #F00;
     100px;
    height: 100px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin: -50px 0 0 -50px;
}
4.absolute定位 加transform 元素未知宽度

如果元素未知宽度,只需将上面例子中的margin: -50px 0 0 -50px;替换为:transform: translate(-50%,-50%);

<div class="box">
    <div class="content">
    </div>
</div>

.box {
    background-color: #FF8C00;
     300px;
    height: 300px;
    position: relative;
}
.content {
    background-color: #F00;
     100px;
    height: 100px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}
5.flex布局 (存在兼容性问题)
<div class="box">
    <div class="content">
    </div>
</div>

.box {
    background-color: #FF8C00;
     300px;
    height: 300px;
    display: flex;//flex布局
    justify-content: center;//使子项目水平居中
    align-items: center;//使子项目垂直居中
}
.content {
    background-color: #F00;
     100px;
    height: 100px;
}
6.able-cell布局

因为table-cell相当与表格的td,td为行内元素,无法设置宽和高,所以嵌套一层,嵌套一层必须设置display: inline-block;td的背景覆盖了橘黄色,不推荐使用

<div class="box">
    <div class="content">
        <div class="inner">
        </div>
    </div>
</div>

.box {
    background-color: #FF8C00;//橘黄色
     300px;
    height: 300px;
    display: table;
}
.content {
    background-color: #F00;//红色
    display: table-cell;
    vertical-align: middle;//使子元素垂直居中
    text-align: center;//使子元素水平居中
}
.inner {
    background-color: #000;//黑色
    display: inline-block;
     20%;
    height: 20%;
}
7.js的事件监听也可以(css可以实现的不推荐使用,出于性能问题考虑)

如果是随屏幕变化,而居中的,也可以使用js

//1.监听轮播左移动距离
window.addEventListener('resize',changeDivLeft,false)
function changeDivLeft(){               
    var w = document.documentElement.clientWidth || document.body.clientWidth;
	var leftRange = (w-1920)/2;//1920是图片容器宽度
//  console.log(w,leftRange);
    $(".swiper-container").css({"left":leftRange});   
}

//2.可简化改版为自执行函数
(function(){
	window.onresize = arguments.callee;
    var w = document.documentElement.clientWidth || document.body.clientWidth;
	var leftRange = (w-1920)/2;//1920是图片容器宽度
    $(".swiper-container").css({"left":leftRange});   
})();
原文地址:https://www.cnblogs.com/missme-lina/p/10218926.html