Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css attribute selectors not working

I have some PHP code that generates a bunch of items like this:

<a href="page.php?day=1&month=1&year=2017"><li>item 1</li></a>

Now I'm trying to select some of them with CSS based on their day= value to give them different styling.

So I tried this CSS code:

a[href*="day=1"] { background-color: grey; }

As per this answer from another post. But it's not doing anything even though it works in the jsfiddle (also from that other post).

What exactly am I doing wrong?

Edit: My actual code obviously does have an element around the <a><li></li></a> elements. The problem is my css doesn't seem to reach my elements. Because when I inspect the an element that should be affected with chrome developer tools it's not showing any trace of the css. I'm thinking it's somehow related to it being php generated

like image 267
frequent_sleeper Avatar asked Aug 22 '26 08:08

frequent_sleeper


1 Answers

Your selector is working fine.

The problem is you've put a block-level element inside an inline-level element.

This causes the browser to close the anchor element before the list item. As a result, the anchor and list item, originally parent and child, are now siblings (spec details below).

Because the anchor is now an empty box with no width, the background color cannot be seen.

Add display: block or inline-block to the anchor.

[href*="day=1"] { background-color: aqua; display: block; }
<a href="page.php?day=1&month=1&year=2017">
  <li>item 1</li>
</a>

Of course, your mark-up is invalid. An li cannot be a child of an anchor element. Only ul, ol and menu can be parents. Consider this instead:

a {
  display: block;
}
a[href*="day=1"] {
  background-color: aqua;
}
<ul>
  <li>
    <a href="page.php?day=1&month=1&year=2017">item 1</a>
  </li>
</ul>

From the spec:

Browser behavior when an inline-level element contains a block-level element.

9.2.1.1 Anonymous block boxes

When an inline box contains an in-flow block-level box, the inline box (and its inline ancestors within the same line box) is broken around the block-level box (and any block-level siblings that are consecutive or separated only by collapsible whitespace and/or out-of-flow elements), splitting the inline box into two boxes (even if either side is empty), one on each side of the block-level box(es). The line boxes before the break and after the break are enclosed in anonymous block boxes, and the block-level box becomes a sibling of those anonymous boxes. When such an inline box is affected by relative positioning, any resulting translation also affects the block-level box contained in the inline box.

like image 136
Michael Benjamin Avatar answered Aug 24 '26 21:08

Michael Benjamin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!