<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>水平垂直的实现</title><style>.wrapper{width:250px;height:250px;border:1px red solid;}.div1{width:50px;height:50px;border:1px blue solid;}</style>
</head>
<body><div class="wrapper"><div class="div1"></div>
</div>
</body>
</html>
上述编码的结果示意图如下所示:
-
采用弹性布局,flex,也就是flexible-box的简称,弹性布局只要在父元素上设置display:flex;align-items:center;justify-content:center即可。这也是最简单的方法了。代码如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>水平垂直的实现</title><style>.wrapper{width:250px;height:250px;border:1px red solid;display:flex;align-items:center;justify-content:center;}.div1{width:50px;height:50px;border:1px blue solid; }</style>
</head>
<body><div class="wrapper"><div class="div1"></div></div>
</body>
</html>
效果图:
-
flex还有一个常用的功能,就是实现两栏布局,左边为固定宽度,右边自适应。代码如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>前端开发面试题</title><link href="StyleSheet1.css" rel="stylesheet" />
</head>
<body><div class="wrapper wrapper-flex"><div class="left">左侧栏,固定宽度200px</div><div class="right">右侧栏,宽度自适应,自适应的意思是加几个字就有多少的宽度</div></div>
</body>
</html>
.wrapper{border:1px solid red;padding:10px 20px;
}.left{width:300px;border:1px solid blue;
}
.right{border:1px solid blue;margin-left:300px;}.wrapper-flex{display:flex;align-items:flex-start;
}
.wrapper-flex .left{flex:0 0 auto;
}
.wrapper-right .right{flex:1 1 auto;
}
效果如下:
更多专业前端知识,请上 【猿2048】www.mk2048.com