日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

解決父元素opacity會影響子元素的問題

作者:田本初 更新時間: 2023-10-12 編程語言

如何使父元素的opacity不影響子元素

前言

現有一個粉紅色父元素,包裹著綠色子元素,效果如下

在這里插入圖片描述

代碼如下

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .border{
		border: 2px solid #333;
      }
      .father {
        width: 400px;
        height: 400px;
        background-color: #CD5C5C;
      }
      .son {
        width: 200px;
        height: 200px;
        background-color: #32CD32;
      }
    </style>
  </head>
  <body>
    <div class="border">
      <div class="father">
        father
        <div class="son">son</div>
      </div>
    </div>
  </body>
</html>

如果一個父元素設置opacity:0.5,那么他的子元素也會受到影響,即使將子元素的opacity設為1也不會正常顯示。

在這里插入圖片描述

在這里插入圖片描述

解決方法

方法一(推薦

將十六進制的顏色轉為rgba寫法,將透明度給rgba的第四個參數

原先寫法

.father{
	width: 400px;
    height: 400px;
    opacity: 0.5;
    background-color: #CD5C5C;
}

修改后寫法

.father{
	width: 400px;
    height: 400px;
    background-color: rgba(205, 92, 92, 0.5);
}

最終效果

在這里插入圖片描述

方法二(可以實現,但沒必要

如果父元素只是一個背景,可以利用定位,使元素脫離文檔流

修改后代碼

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .border {
        position: relative;
        border: 2px solid #333;
      }
      .father {
        position: absolute;
        width: 400px;
        height: 400px;
        background-color: #cd5c5c;
        opacity: 0.5;
      }
      .son {
        position: absolute;
        width: 200px;
        height: 200px;
        background-color: #32cd32;
      }
    </style>
  </head>
  <body>
    <div class="border">
      <div class="father">father</div>
      <div class="son">son</div>
    </div>
  </body>
</html>

在這里插入圖片描述

可以發現最外層的元素由于受到定位影響(子元素脫離文檔流,其本身又未設置高度),導致高度為0,寬度默認100%,還需要手動設置寬高,所以不建議這種寫法。

原文鏈接:https://blog.csdn.net/owo_ovo/article/details/132744753

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新