Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

html - CSS div alternating colour

I'm trying to zebra stripe my divs in my website, sounds simple enough, however I've found that when I added a header in between the rows of my divs it seems to count the header in the odd/even styling

HTML

<div class="container">
    <h3>Title</h3>
    <div class="row">Content</div>
    <div class="row">Content</div>
    <h3>Title</h3>
    <div class="row">Content</div>
    <div class="row">Content</div>
    <div class="row">Content</div>
    <h3>Title</h3>
    <div class="row">Content</div>
    <div class="row">Content</div>
    <div class="row">Content</div>
    <div class="row">Content</div>
</div>

CSS

.container {
    width:600px;
    margin:0 auto;
}

.row {
    line-height:24pt;
    border: solid 1px black;
}

.row:nth-child(odd) {
    background: #e0e0e0;
}

h3 {
    line-height:36pt;
    font-weight:bold;
    color:blue;
}

fiddle

I would have thought that the code already in the fiddle would basically ignore the header and carry on striping, but it appears that it considers the header as a child

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Don't use nth-child, use nth-of-type

div.container > div:nth-of-type(odd) {
    background: #e0e0e0;
}

.container {
  width: 600px;
  margin: 0 auto;
}

.row {
  line-height: 24pt;
  border: solid 1px black;
}

div.container>div:nth-of-type(odd) {
  background: #e0e0e0;
}

h3 {
  line-height: 36pt;
  font-weight: bold;
  color: blue;
}
<div class="container">
  <h3>Title</h3>
  <div class="row">Content</div>
  <div class="row">Content</div>
  <div class="row">Content</div>
  <div class="row">Content</div>
  <h3>Title</h3>
  <div class="row">Content</div>
  <div class="row">Content</div>
  <h3>Title</h3>
  <div class="row">Content</div>
  <div class="row">Content</div>
  <div class="row">Content</div>
  <div class="row">Content</div>
  <div class="row">Content</div>
  <h3>Title</h3>
  <div class="row">Content</div>
  <div class="row">Content</div>
  <div class="row">Content</div>
  <div class="row">Content</div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...