簡體   English   中英

CSS如何更改文本的背景顏色?

[英]CSS How to change background color of text?

我的網頁上只有3個字,我想為其彩色背景:紅色,綠色和藍色。 我的問題有2個組成部分:

  1. 我應該怎么做? 將其放在樣式表中還是僅在網頁中對其進行硬編碼?

  2. 無論哪種方式,請告訴我如何做每種方式,以便我可以決定。 如您所知,我絕對是CSS的初學者。

順便說一句,如果有任何區別,我正在aspx頁面中執行此操作。

對於內聯樣式:

<span style="background-color:red;">Red Stuff...</span>
<span style="background-color:green;">Green Stuff...</span>
<span style="background-color:blue;">Blue Stuff...</span>

對於CSS文件

.red{
  background-color: red;
}

.green{
  background-color: green;
}

.blue{
  background-color: blue;
}

並在您的html中;

<span class="red">red stuff</span>
<span class="green">green stuff</span>
<span class="blue">blue stuff</span>

選擇應該取決於您是否要在其他地方使用這些屬性。 如果是這樣,請使用樣式表。 (恕我直言,無論如何都要使用單獨的樣式表)

您需要將每個單詞放在標簽中,並為每個標簽提供背景色。

像這樣:

<span style="background-color: red;">Word 1</span>
<span style="background-color: green;">Word 2</span>
<span style="background-color: blue;">Word 3</span>

方法1

的HTML

    <div>
     <p id="red">Red</p>
     <p id="green">Green</p>
     <p id="blue">Blue</p>
    </div>

的CSS

    p#red
    {
    background-color: red;
    }

   p#green
    {
    background-color: green;
    }

   p#blue
    {
    background-color: blue;
    }

方法二

的HTML

<p><span>Red</span><span>Green</span><span>Blue</span></p>

的CSS

   p>span:nth-child(1)
   {
   background-color: red;
   }

   p>span:nth-child(2)
   {
   background-color: green;
   }

   p>span:nth-child(3)
   {
   background-color: blue;
   }

將其添加到頭部的HTML中

<link rel="stylsheet" type="text/css" href="#foo" />

為樣式表CSS文件命名,並將相對/絕對路徑放在上述href中

誰能告訴我如何在帖子中添加語法顏色,以便為這個問題添加答案。我將告訴您如何使用c#生成該代碼。

所以代碼是:

string[] cols = { "red","green","blue"} // or any other color
string[] words = { "","","" } // Put your words inside quotes
string res = "";
for(int i = 0;i < 3;i++) 
{
    res+= "<span style=" + "\" + "background-color:" 
    + cols[i] + "\" + " >" + words[i] +  "</span>";
} 
// the code till now should either be in script tags
// or in the code file linked with your web page
// If you are using visual studio that is the name of the pate.aspx.cs
// now use in the aspx page
<% Response.Write(res); %> // I am not sure if the semicolon is required here.

如果您要在服務器端執行此操作。

我建議將其放在樣式表中。 我個人喜歡避免使用任何“硬CSS”(不確定正確的單詞)。

<head>
<style type="text/css">
span.textRed
{
background-color: red;
}
span.textGreen
{
background-color: green;
}
span.textBlue
{
background-color: blue;
}
</style>
</head>
<body>
<span class="textRed"> Red </span>
<span class="textGreen"> Red </span>
<span class="textBlue"> Red </span>
</body>

暫無
暫無

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

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