本文主要是介绍解决当有父盒子存在,给子盒子加margin时不生效的问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题:创建了三个盒子,是三代关系,但是给所有的div加外边距时,子盒子的外边距不生效
代码:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>*{margin: 0%;padding: 0%;}#box{width: 500px;height: 500px;background-color: blue;}#parent{width: 300px;height: 300px;background-color:green;}#child{width: 100px;height: 100px;background-color: red;}div{margin:50px;}</style>
</head>
<body><div id="box"><div id="parent"><div id="child"></div></div></div>
</body>
</html>
结果:
解决办法:在父盒子身上加:overflow:hidden;
加上以后的代码:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>*{margin: 0%;padding: 0%;}#box{width: 500px;height: 500px;background-color: blue;overflow: hidden;}#parent{width: 300px;height: 300px;background-color:green;overflow: hidden;}#child{width: 100px;height: 100px;background-color: red;}div{margin:50px;}</style>
</head>
<body><div id="box"><div id="parent"><div id="child"></div></div></div>
</body>
</html>
结果:
这篇关于解决当有父盒子存在,给子盒子加margin时不生效的问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!