Home > Mobile >  get last child when using Flex order Css
get last child when using Flex order Css

Time:08-11

I am not able to detect last child when using flex order to rearrange divs. since I have arranged order of CSS with Order. its still getting the last child as per dom tree. items divs are dynamic. so we cant use nth-child. how should I get the last child when rearranged with order. There can be multiple items that need to be shown on top. I need CSS or js based solution. my code

    <div >
     <div >first</div>
     <div >second</div>
     <div >third</div>
     <div >fourth</div>
     <div >fifth</div>
     <div >Six</div>
     <div >Seven</div>
    </div>

    <style>
    .mainWrap {display:flex; flex-direction: column;}
    .mainWrap .item {order:2; border-bottom:1px solid #ccc}
    .mainWrap .item:last-of-type {border-bottom:none;}
    .mainWrap .item.orderFirst {order:1;}
    </style>

CodePudding user response:

You could reverse your borders like this:

.item {
  order: 2; // this seems wrong by the way
  border-top: 1px solid #ccc; // set the TOP border on every .item
}

.item.orderFirst {
  order: 1;
  border-top: none; // unset it for the (visually) first element
}

If your actual use-case is as simple as the example, this should give you what you want.

CodePudding user response:

If you're really determined to do it like this, you can use javascript to find the last element that doesn't have the orderFirst class and style that. This does seem like a mis-use of the order property, though.

const mainWrap = document.querySelector(".mainWrap");

const children = [...mainWrap.children];
const ordered = children.filter((c) => !c.classList.contains("orderFirst"));

const last = ordered.pop();
last.style.setProperty("border-bottom", "none");
.mainWrap {
  display: flex;
  flex-direction: column;
}

.item {
  order: 2;
  border-bottom:1px solid #ccc;
}

.item.orderFirst {
  order: 1;
}
<div >
  <div >first</div>
  <div >second</div>
  <div >third</div>
  <div >fourth</div>
  <div >fifth</div>
  <div >Six</div>
  <div >Seven</div>
</div>

CodePudding user response:

You mean to delete the border of the last visible element and not the last element of the div container mainWrap, right?

.mainWrap {display:flex; flex-direction: column;}
.mainWrap > div { order:2; border-bottom: 1px solid #ccc }
.mainWrap > div:nth-last-child(2) { border-bottom:none; }
.mainWrap > div:last-child { order:1; background: red;}
 <div >
     <div >first</div>
     <div >second</div>
     <div >third</div>
     <div >fourth</div>
     <div >fifth</div>
 </div>

  • Related