How To Determine If A DIV is the Last One In Any Given Row


#1

I have a group of DIVs that are aligned horizontally and they will break and go to the next line when the page width shrinks. Each DIV is surrounded by a border and I wanted to prevent borders of adjacent DIVs from doubling up so I removed the right border of each DIV except for the last DIV of the group which is given a border on all four sides.

The problem is when the page width is decreased and the row of DIVs breaks and some DIVs remain in the same row while others go to the rows below it, the last DIV of each row except for the last DIV in the entire group, will now be without a right border. How can I use Javascript to determine if a DIV is the last DIV in any given row so that I can give it a right border dynamically?


#2

Hi @oangodd,

You can actually do this solely with CSS last-child selector:

.myContainer > div:last-child {
border-right:1px solid black;
}

Hope it helps


#4

Hi Andre, thanks for replying but you misunderstood my question. I'm not trying to give the last DIV of the group a right border. What I'm trying to do is give the last DIV of any row a right border if it did not already have one.


#5

Hi @oangodd sorry for misunderstanding I must have read it a little too fast...
In that case the only way that comes to mind is if you took control of how many elements per row display at any given time. You could do this with pure CSS and media queries and the nth-child selector will also come in handy for your borders: https://css-tricks.com/almanac/selectors/n/nth-child/

Why I'm not suggesting JS is because, although possible it is a little bit convoluted as you would have to listen for window resize events, and make sure you're doing things optimally which could become a little overcomplicated for the purposes of only just adding a border.

Are your divs fixed or fluid width?
Is there any chance we could have a look at a working demo? That way it will be easier to help...


#6

You can usually do this with a negative margin but we’d need to see your existing html and css.

Here's a simple codepen showing various solutions.


#7

Hi Paul, Thanks for replying. I was floating my DIVs to the left and when I use your solution which uses float, the effect that I was going for was achieved. Thanks for all your help.


closed #8

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.