簡體   English   中英

調整父div的高度取決於子div

[英]Adjust height of parent div depends on the child divs

我希望我的父級高度在具有1或2個子div時是自動的,並且如果其大於3 div將具有特定的高度。 怎么做? 可能嗎?

<div class="parent-div"> 
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

SCSS

.parent-div {
  height: 370px;
  overflow: auto;
  overflow-x: hidden;
  padding-right: 25px;
  margin-bottom: 7px;

  &:nth-child(n+1) ~ div {
    height: auto;
    overflow: hidden;
  }
}

在“頁面加載”上下文中,使用JavaScript查找div並計算其內容。 然后根據需要應用CSS。

設置最大高度將始終限制高度,即使只有一個或兩個div時也是如此。

當前尚無法使用純CSS設置元素父元素的樣式。

如果您知道渲染HTML期間的項目數量,或者在DOM更改時有方法修改類,則可以創建一些修飾符類,並將其與基類一起使用。

.parent-div {
  padding-right: 25px;
  margin-bottom: 7px;
}

.parent-div-few {
  /*
   * Not even needed, auto is the initial value.
   */
  height: auto;
}

.parent-div-lot {
  /*
   * Not even needed, auto is the initial value.
   */
  height: 370px;
  overflow: auto;
  overflow-x: hidden;
}

並針對兩種不同情況使用不同的HTML結構:

<div class="parent-div parent-div-few">
  <div class="child">
  <div class="child">
<div>

<div class="parent-div parent-div-lot">
  <div class="child">
  <div class="child">
  <div class="child">
<div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM