Misha Moroshko
Misha Moroshko

Reputation: 171489

How to change background color of numbers in ordered list?

Using Javascript, I would like change the background color of the numbers in an ordered HTML list. The background color of the list content should not change. How can I achieve this ?

Upvotes: 2

Views: 6165

Answers (3)

Pascal MARTIN
Pascal MARTIN

Reputation: 401182

Based on the following article : Style Ordered List with CSS, if you have some HTML code like this :

<ol id="list">
  <li>
    <p>this is some text</p>
  </li>
  <li>
    <p>and some other text</p>
  </li>
</ol>


Then, using a CSS that looks like this :

ol {
  background: red;
}
li {
  background: white;
}
p {
  margin: 0px;
}


Might get you something like what you're asking for : here's the result I get (only tested with Firefox) :


(source: pascal-martin.fr)


(There are more explanations on the article I linked to at the beginning of my answer)


EDIT after the comment : ooops, didn't see that part ; sorry :-(

Now that you have an ordered list, with a specific color as background for the numbers, you can plug-in some Javascript code, to change that color.

Considering that the <ol> tag I used here as id="list", you can change its background-color with the following portion of JS code :

document.getElementById('list').style.backgroundColor = 'blue';

After this is executed, you'll get something that looks like the following :


(source: pascal-martin.fr)

Upvotes: 1

Asher G.
Asher G.

Reputation: 5001

Solutions for ol and ul using HTML and CSS only.

Solution for ul

ul {
    list-style: none;
    display: block;
    padding: 0;
}

ul li::before {
  content: "• ";
  background-color: red;
}

<ul>
  <li>list item1</li>
  <li>list item3</li>
  <li>list item3</li>
</ul>

Solution for ol using counter-increment

ol {
    list-style: none;
    display: block;
    padding: 0;
    counter-reset: my-counter;
}

ol li {
  counter-increment: my-counter;
}

ol li::before {
  content: counter(my-counter) ". ";
  background-color: red;
}

<ol>
  <li>list item1</li>
  <li>list item3</li>
  <li>list item3</li>
</ol>

Upvotes: 1

Sarower Jahan
Sarower Jahan

Reputation: 1495

Above answer is good. but you can create it other way...

<!--HTML-->

<ol class="questions">
       <li><a href="#">What is your biggest fear about marriage?</a></li>
       <li><a href="#">If your friends were asked to describe you in one word what would ...</a></li>
       <li><a href="#">Are you closer to your family or your friends and why?</a></li>
       <li><a href="#">What is the role of a wife?</a></li>
       <li><a href="#">What is the role of a husband?</a></li>
</ol>


/*==============CSS===========*/
.questions li{ 
    list-style-position:inside; 
    margin-top:1px;
    padding:0px 5px;
    background:#e7e2da;
}
.questions li a{
    padding:10px;
    display:block;  
}

Upvotes: 0

Related Questions