How to select and stylize multiple line before specific character with CSS?

Viewed 52

I have these example line in my HTML.

<body>
    <ul>
        <li>Name : John</li>
        <li>Age : 32</li>
        <li>Gender : Male</li>
    </ul>
</body>

Is it possible to select & stylize text before colon only and all leave text after colon unaffected with CSS?

I can't manually insert span of each line because my actual list is way much longer.

2 Answers

You just need to add span, just like this

.my-list li span {
  color: red;
}
<body>
    <ul class="my-list">
        <li><span>Name</span> : John</li>
        <li><span>Age</span> : 32</li>
        <li><span>Gender</span> : Male</li>
    </ul>
</body>

If you don't like this solution, you may have to use javascript to accomplish what you're wanting, but here is an idea.

Add a class to your <ul> element like this. Then remove the "Name:", "Age:", and "Gender:" text from each li tag.

<body>
    <ul class="modifyText">
        <li>John</li>
        <li>32</li>
        <li>Male</li>
    </ul>
</body>

Then add this to your CSS file. This way you can just copy and paste and change the nth-child and the content without manually doing each one.

.modifyText li:nth-child(1)::before  {
 color: black;
 font-weight: bolder;
 content: "Name: ";
}
.modifyText li:nth-child(2)::before  {
 color: black;
 font-weight: bolder;
 content: "Age: ";
}
.modifyText li:nth-child(3)::before  {
 color: black;
 font-weight: bolder;
 content: "Gender: ";
}
Related