3 回答

TA貢獻1821條經驗 獲得超6個贊
首先,您需要小心您的代碼:
使用短橫線命名 CSS 類名
使用雙倍空格進行縮進
=
設置屬性時不要在周圍添加空格
現在,為了解決您的問題,我認為您需要做的就是重置 h2 元素的邊距,以確??偢叨?h2 + 邊距小于您min-height
為標題容器設置的高度。
嘗試一下,看看是否能解決您的問題:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="my-component-wrapper">
<div class="my-container">
<div class="title">
<h2 class="head-title">This my Header</h2>
</div>
</div>
<div class="image">
<img
class="my-image"
src="https://via.placeholder.com/800x200"
alt=""
/>
</div>
</div>
</body>
</html>
/* style.css */
body {
margin: 0;
padding: 0;
background-color: aqua;
}
.my-image {
width: 100%;
}
.title {
min-height: 60px;
}
.head-title {
margin: 0;
padding: 10px 0;
}

TA貢獻1877條經驗 獲得超1個贊
設置標題的最小高度值,該值等于其行高值。這樣,即使沒有文本內容,標題空間也不會折疊。
.headTitle {
min-height: 40px;
line-height: 40px; // set these values as you want, they just need to be equal
}
<div class = "myComponentWrapper">
<div class = "myContainer"
<div class = "Title">
<h2 class = "headTitle"> This my Header</h2>
</div>
</div>
<div class "image">
<img class="myImage" .......>
</div>
</div>

TA貢獻1802條經驗 獲得超4個贊
可能有多種方法可以做到這一點。我將描述一個我認為簡單的例子。
使用條件邊距
您可以(通過檢查)找出標題的高度加上標題和圖像之間的間隙,然后您可以做的是將條件邊距頂部應用于類來實現它.image。
假設標題 + 間隙的高度為 40px,間隙本身為 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;
}
您還可以為標頭元素指定特定的高度,然后此計算對您來說會變得更容易,而不是通過檢查來查找所占用的垂直空間。
注意:如果您沒有為其指定特定高度,您還需要擔心line-height元素的高度。h2在這種情況下,您需要添加計算的標題line-height和圖像之間的間隙,然后使用它代替margin-top40px,如上所示。
更新:
如果我所做的假設是錯誤的,那么您就不能使用同級選擇器來應用這些規則。在這種情況下,您需要更改標記以使標題和圖像成為同級,或者可以選擇更復雜的路線并使用 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';
}
添加回答
舉報