Yummi
Yummi

Reputation: 117

How can I set an element's background-color in an HTML file?

Is it possible to set an element's background-color without a CSS file? Just using an HTML file?

In this case, I have a div I want to style. But I could want to style other elements in the future.

body {
    background-color: #6B6B6B;
    margin: 50px;
    
    font-family: Arial;
    color: white;
    font-size: 14px;
    font-weight: 100;
    line-height: .2;
    letter-spacing: 1px;
}
<div style="height:100px;" style="background-color:red;">text</div>

Upvotes: 5

Views: 73678

Answers (3)

Rayees AC
Rayees AC

Reputation: 4659

You are using two style attributes on a single div element, which is invalid:

<div style="height:100px;" style="background-color:red;">text</div>

Instead, use (if using different CSS styles, separate them by ; like below)

<div style="height:100px;background:red;">text</div>

You can use inline CSS in the HTML, or by using the bgColor attribute.

You can use the bgColor attribute, like bgColor="#6B6B6B", in the body element to change the background-color of <body>.

The HTML bgcolor attribute is used to set the background color of an HTML element. Bgcolor is one of those attributes that has become deprecated with the implementation of Cascading Style Sheets.

It Supports tags like

<body>,<marquee>, <table>, <tbody>,<td>,<tfoot>,<th>,<thead>,<tr>

DEMO USING bgColor:

<body bgColor="#6B6B6B">
  <div style="height:100px;background:red;">text</div>
</body>

DEMO WITHOUT USING bgColor:

<body style="background:#6B6B6B">
  <div style="height:100px;background:red;">text</div>
</body>

NOTE:

You can add background color by using background and background-color property in CSS

Upvotes: 6

Beginner
Beginner

Reputation: 50

Add this CSS

body {
    background-color: #6B6B6B;
    margin: 50px;
    font-family: Arial;
    color: white;
    font-size: 14px;
    font-weight: 100;
    line-height: .2;
    letter-spacing: 1px;
}
.mydiv {
    background:red;
    padding:5px;
    color:white;
}

In HTML

<div class="mydiv">text</div>

Upvotes: 1

wak786
wak786

Reputation: 1625

Working Code

body {
    background-color: #6B6B6B;
    margin: 50px;
    
    font-family: Arial;
    color: white;
    font-size: 14px;
    font-weight: 100;
    line-height: .2;
    letter-spacing: 1px;
}
<div style="height:100px;background-color:red">text</div>

Your syntax was broken for inline styles. You were specifying styles two times.

Upvotes: 1

Related Questions