Artemkller545
Artemkller545

Reputation: 999

CSS List - align list elements perfectly into the width with an equal gap between them

Let's keep this simple and short, I've made 2 dummy examples of my problem.

I have a container section which is 600px wide, this section will container list of products.

each product is a 100x100 block, and there is a margin of 62px between each product.

The ul is set on display: inline-block so it won't go one under each other.

Now in the following pen example: http://codepen.io/anon/pen/yujLf You can see what I want to do, can you see how the first row of squares, touch the border of the container & then the next element goes under?

img
(source: gyazo.com)

You can see how it's perfectly aligned for the width, as there's a perfect equal margin between each element.

Now this solution is a problem, because now the second row will have extra margin on the left side:

img
(source: gyazo.com)

I do have a solution for that, simply by changing margin-left to margin-right and disable margin-right for ul li:last-child.

But if I do that, I will not be able to align the last element with the border, like I did with the first example, take a look: http://codepen.io/anon/pen/wdhrJ

As you see, I had to change the margin to 40px instead of 62px to make it 4 elements per row.

Is it possible to implement what I want with using ul?

Upvotes: 1

Views: 551

Answers (2)

user652649
user652649

Reputation:

Have you tried this hack instead? http://codepen.io/anon/pen/IgKtD

* {
  padding: 0;
  margin: 0;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
  text-align:justify;
  vertical-align:top;
  font-size:0.001px;
}

ul::after {
  content:'';
  display:inline-block;
  width:100%;
  height:3px;
  background:blue;
}

ul li {
  width: 100px;
  height: 100px;
  background-color: red;
  display: inline-block;
  box-shadow: inset 0 0 0 1px purple;
  margin:0 20px;
}

ul li:nth-child(4n), ul li:last-child {
  margin-right:0;
}

ul li:nth-child(4n-3) {
  margin-left:0;
}

Upvotes: 6

TylerH
TylerH

Reputation: 21092

If your container is fixed at 600px, then the following solution will work:

ul li {
    width: 100px;
    height: 100px;
    background-color: red;
    margin-right: 62px;
    display: inline-block;
}

ul li:nth-child(4n+4) {
    margin-right: 0;
}

What I've done is change margin-left to margin-right in both of the above selectors. I've also changed your second selector from first-child to nth-child, to select the 4th element and every 4th element after that.

CodePen Example

Upvotes: 10

Related Questions