trinity
trinity

Reputation: 52

css preprocessors with less

I just started working with less and am trying to work on some simple boxes to get a better understanding. There are 4 boxes with different colors and sizes however on the div:nth-child(2) it always creates two boxes. How can I fix it to make one box?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CSS Preprocessors</title>
    <link rel="stylesheet" href="less/style.css">
</head>
<body>
<nav>Navigation Bar</nav>
<div class="container">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>
<footer>Footer</footer>
</body>
</html>
*{
  margin: 0;
}

html{
  background-color: @mainColor;

}

.container {
  min-height: 50vh;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

  div:nth-child(1){
    .boxes(@box1Color, 100px)
  }

  div:nth-child(2){
    .boxes(@box2Color, 200px)
  }

  div:nth-child(3){
    .boxes(@box3Color, 250px)
  }

  div:nth-child(4){
    .boxes(@box4Color, 50px)
  }

with the container and without the second nth child the page looks completely fine but when the second box is added everything condenses and the a big box goes behind the regular boxes

.boxes(@color, @wh){
  border-radius: 8px;
  border: solid black 2px;
  background-color: @color;
  height: @wh;
  width: @wh;
}

boxes in question

Upvotes: 0

Views: 76

Answers (1)

Johannes
Johannes

Reputation: 67748

Instead of this selector...

div:nth-child(2){
 .boxes(@box2Color, 200px)
}

...you should be more specific, since that will apply to all DIVs which are a second child of anything else.

Use the class of your parent container in a combined selector to limit the selection to children of that container, like this:

div.container > div:nth-child(2){
 .boxes(@box2Color, 200px)
}

And similar for the other children.

In LESS you can also write that (and your other child-selector rules) as

div.container {
  &>div:nth-child(1){
    .boxes(@box1Color, 100px)
  }
  &>div:nth-child(2){
    .boxes(@box2Color, 200px)
  }
  &>div:nth-child(3){
    .boxes(@box3Color, 250px)
  }
  &>div:nth-child(4){
    .boxes(@box4Color, 50px)
  }
}

P.S.: Actually, the main mistake in your code is that you are closing the rule for .container directly after the settings instead of moving that closing bracket (}) to after the rules for the child divs.

My LESS code above is also a little bit more specific by also using the direct child selector > combined with the & placeholder for the parent in the rules for the children.

Upvotes: 1

Related Questions