skip to Main Content

I have three div classes. something like this

.first {border: 1px solid #ccc; width: 800px}
.second {width:200px;float:left;}
.third {margin-left:10px}

<div class="first"><div class="second"><img src="https://dummyimage.com/200x300"></div><div class="third">test</div>

here second div shows from the left side. I want the third div class margin-left count from the second div class. is it possible?

2

Answers


  1. Would you like to set the margin of the third div class and calculate from the second div class? yes, it’s possible to do. you can use the html as like below.

    <div class="first">
      <div class="container">
        <div class="second"><img src="https://dummyimage.com/200x300"></div>
        <div class="third">test</div>
      </div>
    </div>
    

    and the CSS, you should have to set the margin for the third div with the container such as this below CSS.

    .first { border: 1px solid #ccc; width: 800px; }
    .second { width: 200px; float: left; }
    .container .third { margin-left: 10px; }
    

    here the margin is using for the third div class and it will be calculated from second div class coz, both are with the same container.

    Login or Signup to reply.
  2. You can easly make them stay next to each other using display: flex; at parent element
    and add flex-shrink: 0; at image container to prevent it from lose width if sibling(element with text) is too big

    .first
    {
      border: 1px solid #ccc;
      width: 800px;
      display: flex;
    }
    .second
    {
      width:200px;
      flex-shrink: 0;
    }
    .third
    {
      margin-left:10px
    }
    <html>
    <body>
    
    <div class="first">
      <div class="second">
        <img src="https://dummyimage.com/200x300">
      </div>
      <div class="third">
        test
      </div>
    </div>
    
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search