Home > Net >  Why does my division styling style 2 child elements even though i placed a first-child tag?
Why does my division styling style 2 child elements even though i placed a first-child tag?

Time:08-24

So i have a div with 2 columns and images in both of them,and i want only the first image to have a margin.

HTML code:

      <div >
    <div >
      <img src="assets/images/images/crop-1.png">
    </div>
  </div>
  <div >
    <div >
      <img src="assets/images/images/sliced-2.png">
    </div>
  </div>

CSS portion:

    div.center img:first-child{
  margin-left:100px;
}

The only problem is,the first child selector isn't working as intended and styles both of my images and give them a margin...How do i Fix this?

CodePudding user response:

You css isn't working because both of your img elements are the first child inside of their parent. What you maybe want is to add a margin to the image inside of the first column.

Something like

    .column:first-child img {
        margin-left: 100px;
    }

Without seeing the rest of your html i cannot know if this will work correctly. It will only work if the first column is indeed the first child inside its parent.

Another solution would be for you to add classes to your images, something like

<div >
    <div >
        <img  src="assets/images/images/crop-1.png">
    </div>
</div>
<div >
    <div >
        <img  src="assets/images/images/sliced-2.png">
    </div>
</div>

and then

.image--with-margin {
    margin-left: 100px;
}

CodePudding user response:

you can wrap the columns in a container div and target only the first column

html:

    <div >
  <div >
    <div >
      <img src="assets/images/images/crop-1.png">
    </div>
  </div>
  <div >
    <div >
      <img src="assets/images/images/sliced-2.png">
    </div>
  </div>
</div>

and css:

.container .column:first-of-type img {
  margin-left: 100px;
}
  •  Tags:  
  • css
  • Related