target a div without a class or id [closed]

2020-04-30 03:24发布

Does any one know how I can target a div, and style it, when it is in another div and it has no id or class.

<div class="wrapper">
    <div>
    </div>

    <div>
    </div>

    <div>
    </div>
</div>

How do I target div two for example.

标签: html css
4条回答
等我变得足够好
2楼-- · 2020-04-30 03:35
.wrapper > div:nth-child(1) {
  //css rules for a div that is the first child of .wrapper
}

.wrapper > div:nth-child(2) {
  //css rules for a div that is the second child of .wrapper
}

Note the > is necessary, otherwise it will target any descendent divs (grandchildren, etc) instead of just direct children.

查看更多
▲ chillily
3楼-- · 2020-04-30 03:38
.wrapper div:nth-child(2) {
    color: red;
}

nth-child allows you to select specific items. There is also first-child and last-child for selecting the first/last item.

The number 2 can also be a function like 3n+0. This selects every third item starting from 0. Check out this codepen for an example.

Last but not least, you also have nth-of-type(2). This will change every second item every time the same pattern appears. I have also included an example in the same codepen.

查看更多
劳资没心,怎么记你
4楼-- · 2020-04-30 03:42

Descendant Selectors are the Worst, not only is this not performant but it is fragile, as changes to the HTML can easily break your CSS. It is preferable to simply create a new CSS class selector.

// bad
.wrapper div {..}

// good
.inner-div {..}
.selecting-this {..}
.or-this {..}

<div class="wrapper">
    <div class="inner-div">
    </div>

    <div class="selecting-this">
    </div>

    <div class="or-this">
    </div> 

    <div class="inner-div">
    </div>
</div>

But if you can't modified the html:

.wrapper div {..}

if there is space in selector, it searches for children elements with tag div INSIDE element with given class .wrapper

Check this out fore more information. http://modernweb.com/2013/08/12/writing-better-css/?utm_source=html5weekly&utm_medium=email

查看更多
欢心
5楼-- · 2020-04-30 04:02
.wrapper div:nth-child(2) {
  background: blue;
  height:200px;
  width:200px;
}

Whatever number you pass into the nth-child targets #wrappers specific children. So the second div in your case.

Reference: http://www.w3schools.com/cssref/sel_nth-child.asp

查看更多
登录 后发表回答