CodeName44
CodeName44

Reputation: 49

Add border to odd div's using CSS

I have a html like

<div class="wrap">
  <div class="single_wrap">
     <div class="single_div">
         <p>some text</p>
     </div
  </div>
  <div class="single_wrap">
     <div class="single_div">
         <p>some text</p>
     </div
  </div>
  <div class="single_wrap">
     <div class="single_div">
         <p>some text</p>
     </div
  </div>
  <div class="single_wrap">
     <div class="single_div">
         <p>some text</p>
     </div
  </div>
</div>

And CSS

.wrap { float:left; width:100%;}
.single_wrap { float:left; width:50%; padding:15px 0; border-bottom:1px solid #ccc;}
.single_div { float:left; width:100%; border-right:1px solid #ccc;}

now what I want to achieve is border-right to every odd .single_div and border-bottom to all but last two .single_wrap. How to achieve this using CSS. I know nth selector but it doesnt work. as i tried something like this

.single_wrap .single_div:nth-child(odd) { border-right:1px solid #ccc;}

Upvotes: 1

Views: 1369

Answers (2)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123367

You should first check your markup, since there're unclosed div. Then for your purpose on recent/modern browser you could do it like so

/* right border on all odd single_div */
.single_wrap:nth-child(2n + 1) .single_div {
  border-right: 1px #000 solid;
}

/* bottom border on first n-2 single_wrap */
.single_wrap:nth-last-child(n + 3) {
  border-bottom: 1px #000 solid;  
}

Example fiddle: http://codepen.io/anon/pen/raMVgM

Upvotes: 2

Weafs.py
Weafs.py

Reputation: 22992

Use .single_wrap:nth-child(odd) .single_div selector. For border-bottom use :nth-child(1) and nth-child(2).

.wrap {
  float: left;
  width: 100%;
}
.single_wrap {
  float: left;
  width: 50%;
  padding: 15px 0;
}
.single_div {
  float: left;
  width: 100%;
}
.single_wrap:nth-child(odd) .single_div {
  border-right: 1px solid #ccc;
}
.single_wrap:nth-child(1) .single_div, .single_wrap:nth-child(2) .single_div {
  border-bottom: 1px solid #ccc;
}
<div class="wrap">
  <div class="single_wrap">
    <div class="single_div">
      <p>some text</p>
    </div>
  </div>
  <div class="single_wrap">
    <div class="single_div">
      <p>some text</p>
    </div>
  </div>
  <div class="single_wrap">
    <div class="single_div">
      <p>some text</p>
    </div>
  </div>
  <div class="single_wrap">
    <div class="single_div">
      <p>some text</p>
    </div>
  </div>
</div>

Upvotes: 1

Related Questions