学习目标:

如何在一个大的div盒子里面设置左右两边两个小div盒子。

学习内容:

1、 通过flex实现效果 2、 通过浮动实现效果 3、 通过绝对定位实现效果

方法一:

通过flex布局实现:
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>通过flex布局实现</title>
	</head>
	<body>
	<div class="big_box">
		<div class="left_box">我是左边的盒子</div>
		<div class="right_box">我是右边的盒子</div>
	</div>
	</body>
	<style>
		.big_box{width: 400px;height: 400px;background-color: blue;display: flex;}/* 设置大盒子的布局为flex布局 */
		.left_box{width: 200px;height: 200px;background-color: gold;}
		.right_box{width: 200px;height: 200px;background-color: greenyellow;}
	</style>
</html>

效果图:
在这里插入图片描述

方法二:

通过左浮动有浮动来实现:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>通过浮动实现</title>
	</head>
	<body>
	<div class="big_box">
		<div class="left_box">我是左边的盒子</div>
		<div class="right_box">我是右边的盒子</div>
	</div>
	</body>
	<style>
		.big_box{width: 400px;height: 400px;background-color: blue;}
		.left_box{width: 200px;height: 200px;background-color: gold;float: left;}/* 左边模块左浮动 */
		.right_box{width: 200px;height: 200px;background-color: greenyellow;float: right;}/* 右边模块右浮动 */
	</style>
</html>

(效果图同方法一)

方法三:

通过绝对定位来实现:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>通过绝对定位实现</title>
	</head>
	<body>
	<div class="big_box">
		<div class="left_box">我是左边的盒子</div>
		<div class="right_box">我是右边的盒子</div>
	</div>
	</body>
	<style>
		body{padding: 0px;margin: 0px;}/* 先消除游览器本身的边距 */
		.big_box{width: 400px;height: 400px;background-color: blue;}
		.left_box{width: 200px;height: 200px;background-color: gold;display: inline-block;}/* display:inline-block的目的是将对象呈递为内联对象 (div不再占一整行了)*/
		.right_box{width: 200px;height: 200px;background-color: greenyellow;display: inline-block;position: absolute;left: 200px;}/* 通过绝对定位放置div的位置 */
	</style>
</html>

(效果图同方法一)

总结:

因为div属于块级元素,所以它默认会占一整行,所以要实现div里面的div左右两边布局需要改变div的样式。目前总结出上文三种比较常用的方法,当然远远不止上面所说的方法,其他的可以在以后慢慢发现。
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐