skip to Main Content

I have two DIV elements. I will call them DIV A and DIV B. I am creating a space between the two DIVs of 20px. Example margin-top: 20px. Here is a diagram to show that.
diagram
Let’s say if DIV A is not present in the page, or is removed. In that case, I don’t want to have 20px spacing from DIV B to it’s parent DIV. I just want to use whatever the default spacing is.

I am wondering if there is a way to automatically change spacing for this scenario using CSS?

2

Answers


  1. Use margin-bottom: 20px on div A. In this way, if div A is not present the 20px spacing will also not be present.

    Login or Signup to reply.
  2. Use display: flex; + flex-direction: column on the container. Then you can create the spacing by adding the gap property:

    // for demonstration purpose only 
    document.querySelector('button').addEventListener('click', function() {
      document.querySelector('#A').style.display = 'none';
    })
    body {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }
    
    
    /* for visualization purpose only */
    div {
      border: 2px dashed red;
      min-height: 30vh;
    }
    <div id="A">A <button>Remove DIV</button></div>
    <div id="B">B</div>

    Alternatively you could use a combination of CSS-Selectors:

    // for demonstration purpose only 
    document.querySelector('button').addEventListener('click', function() {
      document.querySelector('#A').style.display = 'none';
    })
    div:not(:last-child) {
      margin-bottom: 20px;
    }
    
    /* for visualization purpose only */
    div {
      border: 2px dashed red;
      min-height: 30vh;
    }
    <div id="A">A <button>Remove DIV</button></div>
    <div id="B">B</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search