How to select the last div in css

余生长醉 提交于 2021-02-08 13:16:16

问题


I have this html code:

<div id="mydiv">
    [other divs]
    <div data-day="1">content</div>
    [other divs with data-day attribute]
    <div data-day="random">content</div>
    [other divs]
</div>

I wanna select the last element in the mydiv that has data-day attribute. How can I do this?

#mydiv div[data-day]:last-child

I tried this, but it didn't work.


回答1:


There is no real css-only solution to your question. With Javascript you could do this, I guess.

  • last-child doesn't work, because it only works for the last element of its parent.
    In your case: Only if it was the last element with no other element following it.
  • last-of-type doesn't work, because it only selects by types, not attributes or classes.

Workaround:

Add a class to the last element with a certain attribute by hand:

<div id="mydiv">
    <div></div>
    <div data-day="1">content</div>
    <div></div>
    <div data-day="random" class="last-data-day">content</div>
    <div></div>
</div>



回答2:


I have done a quick google search and found the following links useful:

CSS Tricks

Stack Overflow (User with same issue)

The answer is:

:last-child only works when the element in question is the last child of the container, not the last of a specific type of element. For that, you want :last-of-type

http://jsfiddle.net/C23g6/3/



来源:https://stackoverflow.com/questions/20816482/how-to-select-the-last-div-in-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!