可能有多种方法可以做到这一点。我将描述一个我觉得简单的。
使用条件边距
您可以找出(通过检查)标题的高度以及标题和图像之间的间隙,然后您可以将条件边距顶部应用于.image 类来实现它。
假设 header + gap 的高度是 40px,而 gap 本身是 20px,这就是你可以做的。
/* We give this margin-top by default. This includes header height + gap*/
.image {
margin-top: 40px;
}
/* If there's myContainer div, which i am assuming only comes in when you have the header, we reduce that margin top to 20px to compensate for the header that exists.*/
.myContainer + .image {
margin-top: 20px;
}
你也可以给你的标题元素一个特定的高度,然后这个计算对你来说会变得更容易一些,而不是通过检查来找到占用的垂直空间。
注意:如果您没有为其指定特定高度,您还需要担心h2 元素的line-height。在这种情况下,您需要添加计算出的line-height 以及标题和图像之间的间隙,然后将其用作margin-top 而不是如上所示的 40px。
更新:
如果我所做的假设是错误的,那么您就不能使用兄弟选择器来应用这些规则。在这种情况下,您需要更改标记以使标题和图像作为兄弟姐妹,或者可能选择更复杂的路线并使用 JavaScript(不是首选)。
从语义上讲,如果可以的话,我希望将它们保留为兄弟姐妹(假设我可以控制标记生成)。在那种情况下,它看起来像这样。
<div class = "myContainer"
<div class = "Title">
<h2 class = "headTitle"> This my Header</h2>
</div>
<div class "image">
<img class="myImage" .......>
</div>
</div>
然后我会使用相同的兄弟选择器技巧来完成任务。
JavaScript方式
如果您无法控制标记生成,则可以使用 JS 有条件地应用边距。
// Rough example of what you can do assuming the height of header is 20px.
// If you want to find out the height of header dynamically, use
// ```header.offsetHeight``` and add that with 20px(assumed gap height) and apply that as margin top.
const header = document.querySelector(".headTitle");
const image = document.querySelector(".image");
if(header) {
image.style.marginTop = '20px';
} else {
image.style.marginTop = '40px';
}