Home > Net >  Keep the same margin even if an extra element is added to html
Keep the same margin even if an extra element is added to html

Time:09-22

I created a simple example in codesandbox. link: Result

CodePudding user response:

You can do it by using relative/absolute positioning (you can read more about position here):

  1. Make the parent component positioned relative
  2. Make the error element positioned absolute and use left, right, transform in order to position it in the desired place

I've edited your CSS:

.App {
  font-family: sans-serif;
  text-align: center;
}

.container {
  display: flex;
  flex-direction: column;
  
  /* parent relative */
  position: relative;
}

.section {
  margin-bottom: 2rem;
}

.error {
  color: red;

  /* child absoluet */
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translate(-50%, 100%);
}

.blueContent  {
  background-color: blue;
  color: forestgreen;
  min-height: 200px;
}

CodePudding user response:

You can set a min-height on your error element:

.error {
  color: red;
  min-height: 2rem;
}

CodePudding user response:

If I was you.. I would only use CSS. And you can achieve this by using position: absolute;

    .error {
      color: red;
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      transform: translateY(100%);
    }
  • Related