Search code examples
htmlcsscss-selectorscss-specificity

How to successfully target the second part of a string in a span tag with specificity


I understand the easiest way is to "class" something and then give the class the properties needed, however,

1. I'm not a big fan of creating classes everywhere. That's what specificity and CSS mapping is for.

2. It would take me forever to go through hundreds of pages to add these classes and some of the pages I'm not even supposed to even touch AT ALL!

So, at least I have a parent class to start with :) But my problem is, I have never had to target the second part of a text inside span tags divided by a <br> .

Here is the HTML

<div class="locations">
<ul>
    <li><strong>Address: </strong><span>47 Feed Mill Lane
        <br>
        Middlebury, VT 05753</span></li>
    <li><strong>Contact: </strong><span>John Doe</span></li>
    <li><strong>Phone: </strong><span>800-639-3191</span>/li>
    <li><strong>E-mail: </strong><span> <a href="mailto:email@email.com">email@email.com</a></span></li>
</ul>

and the CSS for the line in question. I added this specificity logic, but it is taking the entire content inside the <span> I want to select the portion after the <br> so I can indent it.

.locations > ul > li:first-child > span:nth-child(2) {
    background-color: #34678a; /*for testing purposes only */
    text-indent:25px;
}

Here is the FIDDLE

And a little visual doesn't hurt ;) enter image description here


Solution

  • CSS can't read the content of your elements and therefore has no idea where the <br> tag is. Target it instead with display:inline-block; and vertical-align:text-top;

    jsFiddle example

    You can use the following:

    .locations > ul > li:first-child > span:nth-child(2) {
        background-color: #34678a;
        display:inline-block;
        vertical-align:text-top;
    }