merch89 merch89 - 1 month ago 6
CSS Question

Target a custom attribute within a div

I have a set of divs with a number sequence. How can I access a specific number (eg. si=3)

I've tried a few options with no joy. Any other options?

<div id="parentdiv" style="height:500px;>
<div class="child_div" si="1" title="F1" style="top:360px; left:68px;"></div>
<div class="child_div" si="2" title="F1" style="top:360px; left:80px;"></div>
</div>

ATTEMPTS

#parentdiv si[2] {
left:50%;
}

#parentdiv > [si~="2"] {
left:50%;
}

#parentdiv > div[si~="2"] {
left:50%;
}

Answer

Firstly. this #parentdiv [si="2"] does work but position values such as top and left need to have a positioning context.

In this case, the element need to have either position:absolute or position:relative (depending on your requirement) for the position values to work.

Secondly, the inline style will take effect last and so override any linked CSS styles unless additional specificity is applied.

Unfortunately, the only way to override an inline style is with !important.

#parentdiv * {
  position: relative;
}
#parentdiv [si="1"] {
  height: 50px;
  background: orange;
}
#parentdiv [si="2"] {
  height: 50px;
  background: pink;
  left: 50% !important;
}
<div id="parentdiv" style="height:500px;">
  <div class="child_div" si="1" title="F1" style="top:60px; left:68px;">1</div>
  <div class="child_div" si="2" title="F1" style="top:60px; left:80px;">2</div>
</div>