我正在嘗試將 margin-top 應用于 .leaf 類,但 margin 也適用于其父級 我只想將 margin-top 應用于 .leaf 類?
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
.tree {
height: 400px;
width: 400px;
background-color: red;
}
.leaf {
height: 30px;
width: 30px;
background-color: yellow;
margin: 10px;
}
</style>
</head>
<body>
<div class="tree">
<div class="leaf" style="margin-top:100px"></div>
</div>
</body>
</html>
uj5u.com熱心網友回復:
在這種情況下,您可以overflow: hidden;在您的父 div 中使用。
.tree {
height: 400px;
width: 400px;
background-color: red;
overflow: hidden;
}
.leaf {
height: 30px;
width: 30px;
background-color: yellow;
margin: 10px;
margin-top: 100px;
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div class="tree">
<div class="leaf"></div>
</div>
</body>
</html>
uj5u.com熱心網友回復:
您可以使用相對位置:
.leaf {
position: relative;
top: 100px;
height: 30px;
width: 30px;
background-color: yellow;
margin: 100px 10px 10px 10px;
}
uj5u.com熱心網友回復:
邊距不會影響子代相對于其父代的位置,除非父代有填充,在這種情況下,大多數瀏覽器會將子代的邊距添加到父代的填充中。
然后向父元素添加一些填充
.tree {
height: 400px;
width: 400px;
background-color: red;
padding:1px;
}
但是,如果您不需要為父元素應用填充,請放在 子元素之前。
完整答案
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
.tree {
height: 400px;
width: 400px;
background-color: red;
}
.leaf {
height: 30px;
width: 30px;
background-color: yellow;
margin: 10px;
}
</style>
</head>
<body>
<div>
<div class="tree">
<div class="leaf" style="margin-top:100px"></div>
</div>
</div>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/481795.html
