Onome Sotu
Onome Sotu

Reputation: 676

How can i keep the margin/ between to HTML elements constant in the same Div when the size of one changes

I have this issue with margins in HTML elements. This is an example of the code.

<body>
  <div>
    <h1>...some text...</h1>

    <p>..some quote</p>

    <button>New Quote</button>
  </div>
</body>

On click of the button, the quote in <p> changes. So the height of p element increases or decreases depending on the length of the quote. This then moves the position of the button up or down the page. I don't want to button to move up or down. I can do this by putting the button in a separate div but is it possible to set a margin between <p> and <button> such that the position do not change?

Thanks

Upvotes: 0

Views: 1589

Answers (1)

tao
tao

Reputation: 90068

There are several ways to do this and it has absolutely nothing to do with Twitter Bootstrap. It's general HTML + CSS, therefore applying to Twitter Bootstrap, too.

Considering the following generic HTML structure:

<container>
    <quote>
        some quote
    </quote>
    <button>
        some button
    </button>
</container>

... you have the following alternative options:

  1. min-height on <quote>, big enough to cover all current possible heights of your <quote>s
container quote {
  min-height: 50vh;
}
  1. min-height and padding-bottom on <container> and place <button> absolute, to bottom:
container {
  min-height: 50vh;
  padding-bottom: 80px;
  position: relative;
}
container button {
  position: absolute;
  bottom: 15px;
}
  1. min-height on <container> with flexbox column layout with justify-contents:space-between;:
container {
  display: flex;
  flex-direction: column;
  min-height: 50vh;
  justify-contents: space-between;
}

An alternative to justify-contents: space-between, if you prefer your <quote>s to always grow in the available space (i.e. it has a background-color) is flex-grow:1 on <quote>:

container {
  display: flex;
  flex-direction: column;
  min-height: 50vh;
}
container quote {
  flex: 1;
}

Feel free to replace 50vh in the above examples with your desired height (in px, em, rem, cm, in...). Unless it's inside a container with physical height or min-height (expressed in in the above units — a.k.a. hard units) using % will not make your element get the desired height, because it will be % of <body> height, which is not the viewport height - unless specified otherwise, it's the sum of all resulting heights of its normal flow contents.

To understand why <body>s 100% height is not the viewport's 100% height, one would need understand VFM properly (or VBM as I see it called officially now).
A good overview of the spec can be found in this SO Community curated answer.

Upvotes: 4

Related Questions