一篇读懂CSS盒模型

CSS盒模型

1.盒模型的概念

盒子模型,顾名思义就是一种容器,里面可以放内容的容器,例如:快递盒、杯子等,

在html中例如:div里面可以放a标签、span标签等

用官方的话来讲就是:CSS盒模型本质上是一个盒子,封装周围的HTML元素,它包括:边距,边框,填充,和实际内容。常用的盒模型分一下两种:

content-box是符合w3c标准的盒模型,也是默认的盒模型

border-box是不符合w3c标准的盒模型,也称为怪异盒子

2.盒模型的属性

下面来看一下盒模型的几个属性:

  • Margin(外边距) - 清除边框外的区域,外边距是透明的。
  • Border(边框) - 围绕在内边距和内容外的边框。
  • Padding(内边距) - 清除内容周围的区域,内边距是透明的。
  • Content(内容) - 盒子的内容,显示文本和图像。

现在来看一下示例:

①标准盒模型 :box-sizing: content-box;

width/height = content(width/height) + border + padding

标准盒模型中 width跟height都是内容content的宽高

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>盒模型</title>
		<style type="text/css">
			* {
     
     
				box-sizing: content-box;      //IE盒模型
				/* box-sizing: border-box; */   //怪异盒子
			}

			.wrapper {
     
     
				width: 100px;
				height: 100px;
				border: 10px solid red;
				padding: 50px;
				/* margin: 50px; */
			}

			.item {
     
     
				background-color: red;
				width: 20px;
			}
		</style>
	</head>
	<body>
		<div class="wrapper">
			<div class="item">1</div>
			<div class="item">2</div>
			<div class="item">3</div>
		</div>
	</body>
</html>
<script type="text/javascript">
	(function() {
     
     
        //获取父元素的宽度
		let wrapperWidth = document.querySelector('.wrapper').offsetWidth;
        //获取子元素的宽度
		let itemWidth = document.querySelector('.item').offsetWidth;
		console.log(wrapperWidth,'wrapperWidth')  
        // 220 = (100) + (100) + (20) = ((paddingLeft+paddgingRight)+(content)+(borderLeft+borderRight)
		console.log(itemWidth,'itemWidth')		// 20 = width
	})()
</script>

在这里插入图片描述

②怪异盒模型(IE盒模型) :box-sizing: border-box

width/height = width/height (content + border +padding ) +margin

扫描二维码关注公众号,回复: 12366123 查看本文章

怪异盒模型中的width/height是(内容+边框+内边距的宽度/高度)=> (content + border + padding)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>盒模型</title>
		<style type="text/css">
			* {
     
     
				 /* box-sizing: content-box;  */     //IE盒模型
				 box-sizing: border-box;   //怪异盒子
			}

			.wrapper {
     
     
				width: 100px;
				height: 100px;
				border: 10px solid red;
				padding: 50px;
				/* margin: 50px; */
			}

			.item {
     
     
				background-color: red;
				width: 20px;
			}
		</style>
	</head>
	<body>
		<div class="wrapper">
			<div class="item">1</div>
			<div class="item">2</div>
			<div class="item">3</div>
		</div>
	</body>
</html>
<script type="text/javascript">
	(function() {
     
     
        //获取父元素的宽度
		let wrapperWidth = document.querySelector('.wrapper').offsetWidth;
        //获取子元素的宽度
		let itemWidth = document.querySelector('.item').offsetWidth;
		console.log(wrapperWidth,'wrapperWidth')  // 120 = 100 +20 = (100) + (0) + (20)
        ((paddingLeft+paddgingRight)+(content)+(borderLeft+borderRight)
		console.log(itemWidth,'itemWidth')		// 20 = width
	})()
</script>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43937400/article/details/112260674