Question

I am trying to select every img tag within a grid of news articles and I'm using a loop in SASS to add a border to the top of varying color. I have this working in other situations where the child element is a more direct descendant, but I cannot seem to get a syntax that will work in this scenario where my img tags are nested within elements in the section.

Here is my HTML

<section id="newsTiles">
  <div class="col-sm-5 media-body">
    <a class="" href="#">
    <img class="media-object newsTile" src="http://placehold.it/300x200" alt="...">
    </a>
  </div>
  <div class="col-sm-5 media-body">
    <a class="" href="#">
    <img class="media-object newsTile" src="http://placehold.it/300x200" alt="...">
    </a>
  </div>
</section>

Here is my SASS

/* News Tiles */
//## Looping through nth child to set border top color

$colors: $yell, $ltred, $dkblue, $ltblue, $dkbrown, $ltbrown;

@for $i from 1 through length($colors) {
  #newsTiles  div.col-sm-5 .newsTile:nth-of-type(#{length($colors)}n+#{$i}) {
    border-color: nth($colors, $i);
    border-width:6px 0 0 0;
    border-style:solid;
    &:hover{
      opacity: 0.7;
    }
  }
}
Was it helpful?

Solution

Assuming that you want the border on the img elements...

Sass (I pulled some of the properties and the opacity on the :hover out of the loop as it was producing redundant CSS)

$yell: #FF0;
$ltred: #F00;
$dkblue: #00F;
$ltblue: #AAF;
$dkbrown: #880;
$ltbrown: #AA0;

$colors: $yell, $ltred, $dkblue, $ltblue, $dkbrown, $ltbrown;

@for $i from 1 through length($colors) {
  #newsTiles .col-sm-5:nth-of-type(#{length($colors)}n+#{$i}) a .newsTile {
    border-color: nth($colors, $i);
  }
}

#newsTiles .col-sm-5 a {
  .newsTile {
    border-width:6px 0 0 0;
    border-style:solid;
  }
  &:hover .newsTile {
    opacity: 0.7;
  }
}

Compiled CSS

#newsTiles .col-sm-5:nth-of-type(6n+1) a .newsTile {
  border-color: yellow;
}

#newsTiles .col-sm-5:nth-of-type(6n+2) a .newsTile {
  border-color: red;
}

#newsTiles .col-sm-5:nth-of-type(6n+3) a .newsTile {
  border-color: blue;
}

#newsTiles .col-sm-5:nth-of-type(6n+4) a .newsTile {
  border-color: #aaaaff;
}

#newsTiles .col-sm-5:nth-of-type(6n+5) a .newsTile {
  border-color: #888800;
}

#newsTiles .col-sm-5:nth-of-type(6n+6) a .newsTile {
  border-color: #aaaa00;
}

#newsTiles .col-sm-5 a .newsTile {
  border-width: 6px 0 0 0;
  border-style: solid;
}

#newsTiles .col-sm-5 a:hover .newsTile {
  opacity: 0.7;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top