如何僅對父元素套用樣式而不影響子元素的樣式?
P粉827121558
P粉827121558 2023-09-09 16:47:14
0
2
464

在這個例子中,我試著讓父元素更透明,而不改變子元素的不透明度。

<div>
<div className="larger-box">
  <div className = "smaller-box">
 </div>
</div>

這是我目前的CSS樣式:

.larger-box{
  width: 10rem;
  height: 10rem;
  background-color: red;
}
.smaller-box{
  width: 2rem;
  height: 2rem;
  background-color: green;
  opacity: 1 !important;
}

有沒有可能在CSS中實現這個效果?

P粉827121558
P粉827121558

全部回覆(2)
P粉087951442

你可以使用CSS的not

.larger-box:not(.smaller-box) {
  width: 10rem;
  height: 10rem;
  background-color: red;
}

.smaller-box {
  width: 2rem;
  height: 2rem;
  background-color: green;
}
P粉315680565

孩子總是會受到父母的不透明度的影響,所以給它們不同的不透明度的最簡單方法是將它們設為兄弟元素,並將第二個元素絕對定位在第一個元素的上方,從而使每個元素都有自己的不透明度。請注意父包裝div的position: relative。

在這裡,我有一些文字顯示在紅色div的後面,綠色div位於其上方,就像它是一個子元素一樣,但實際上它是一個兄弟元素,因此不受紅色div的不透明度的影響。因此,文字透過紅色div顯示,但不透過綠色div顯示。

.wrapper{
  width: 10rem;
 height: 10rem;
 position: relative;
}

p { padding: 8px}

 .larger-box{
   position: absolute;
  top: 0;
  left:0;
  width: 10rem;
  height: 10rem;
  background-color: red;
  opacity: 0.3
}
 .smaller-box{
  width: 2rem;
  height: 2rem;
  background-color: green;
  opacity: 1;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="wrapper">
   <p>Lorem ipsum dolor sit amet. Sit dicta tempore id quas delectus estitier at voluptatem voluptas sit culpa iste ea voluptatum vero!</p>
  <div class="larger-box"></div>
  <div class = "smaller-box"></div>
</div>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!