Home > Net >  CSS nth of type choosing all images
CSS nth of type choosing all images

Time:03-26

I am trying to have all odd images floating to the left and all eben images floating to the right.

    <section id="about">
        <div >
            <div >
                <img src="img/about1.png" alt="About">
                <h2>About Us</h2>
                <p>Suspendisse efficitur consequat condimentum.</p>
            </div>
            <div >
                <img src="img/about2.jpg" alt="Apporach">
                <h2>Professional Approach</h2>
                <p>Curabitur justo turpis, pellentesque rhoncus dignissim non, consequat eget ante.</p>
            </div>
        </div>
    </section>

To do that, my logic was that every even image whose parent is #about should float to right, etc. Just like this:

#about img:nth-of-type(2n 1){
  float:left;
}

#about img:nth-of-type(2n){
  float:right;
}

It seems though that all images float on the left of the screen which I do not understand. How do I solve this?

CodePudding user response:

Your selectors in this situation need to be .about-item:nth-of-type(2n 1) img and .about-item:nth-of-type(2n) img.

nth-of-type always and only counts its "n" factor inside its own parent element, not for the whole document.

.about-item:nth-of-type(2n 1) img{
  float:left;
}

.about-item:nth-of-type(2n) img{
  float:right;
}
    <section id="about">
        <div >
            <div >
                <img src="img/about1.png" alt="About">
                <h2>About Us</h2>
                <p>Suspendisse efficitur consequat condimentum.</p>
            </div>
            <div >
                <img src="img/about2.jpg" alt="Apporach">
                <h2>Professional Approach</h2>
                <p>Curabitur justo turpis, pellentesque rhoncus dignissim non, consequat eget ante.</p>
            </div>
        </div>
    </section>

CodePudding user response:

You only have one image in your markup so those selectors won't work.

This would be one possible solution:

/* nth-child on the image only if there is multiple. If there is only one you can remove it */
  
.content > .about-item:nth-child(1) > img:nth-child(1) { 
  border: solid black 1px;
  float: left;
}

.content > .about-item:nth-child(2) > img:nth-child(1) { 
  border: solid red 1px;
  float: right;
}

See it working here:

.content>.about-item:nth-child(1)>img:nth-child(1) {
  border: solid black 1px;
  float: left;
}

.content>.about-item:nth-child(2)>img:nth-child(1) {
  border: solid red 1px;
  float: right;
}
<section id="about">
  <div >
    <div >
      <img src="img/about1.png" alt="About">
      <h2>About Us</h2>
      <p>Suspendisse efficitur consequat condimentum.</p>
    </div>
    <div >
      <img src="img/about2.jpg" alt="Apporach">
      <h2>Professional Approach</h2>
      <p>Curabitur justo turpis, pellentesque rhoncus dignissim non, consequat eget ante.</p>
    </div>
  </div>
</section>

  • Related