水平垂直居中的问题 (四种方法)
方法一 :position布局,position设为absolute
给定高度,通过绝对定位方式居中
width: x;height: y;position: absolute; left: 50%;top: 50%;margin-left: -(x/2);margin-top: -(y/2);
方法二 :display:table
父级元素:{ display:table;}
子级元素: { display:table-cell;vertical-align:middle }
代码:
*{margin: 0;padding: 0;}
html,body { width: 100%;height: 100%; }
.wapper{
width: 100%;
height: 100%;
display:table; }
.content{
display:table-cell;
vertical-align:middle;
background: silver;}
方法三 :flex布局
父级元素:{ display:flex;flex-direction:row;justify-content:center;align-items:center;}
子级元素:{flex:1}
代码:
*{margin:0;padding:0; }
body,html {width: 100%;height: 100%;}
.contain{
width:100%;
height:100%;
margin:0 auto;
background: yellow;
display:flex;
flex-direction:row;
justify-content:center;
align-items:center;}
.box{
width:500px;
height: 300px;
line-height: 300px;
text-align: center;
font-size: 16px;
color#fff;
background-color: #f00;
margin:0 auto;}
方法四 :transform 位移布局
父级元素:{ position: relative;}
子级元素:{ position: absolute; left: 50%; top: 50%; transform:translate(-50%,-50%);}
代码:
* {margin: 0;padding: 0;}
html,body { width: 100%; height: 100%; }
.contain{
width:100%;
height:100%;
position: relative;
background: yellow;
}
.box {
width: 500px;
height: 300px;
line-height: 300px;
text-align:center;
font-size: 16px;
color: #fff;
background: orange;
position: absolute;
left: 50%;
top: 50%;
transform:translate(-50%,-50%);
}
两栏布局: 左边固定,右边自动
效果图:
方法一:浮动
方法二:flex 弹性布局
.main {width: 100%;height: 200px;display: flex;}
.left {width: 200px;height: 200px;background: gray;flex: none;}
.right {height: 100%;background: green;flex: 1; }
方法三:table方法
*{ margin: 0;padding: 0; }
.main { width: 100%; height: 200px; display: table}
.left { width: 200px; height: 200px; display: table-cell;background: yellow;}
.right { height: 100%; display: table-cell; background: orange; }
方法四: css计算宽度calc
*{ margin: 0;padding: 0; }
.main { width: 100%; height: 200px; display: table}
.left { width: 200px; height: 100%; background: yellow; float: left}
.right { height: 100%; background: orange; float: right;width:calc(100% - 200px); }
两栏布局: 左右固定
.left {width: 200px; height: 200px; background: pink; position: absolute; left: 0; }
.right { width: 200px; height: 200px; background: red; position: absolute; right: 0; }
三栏布局: