CSS: make the width of the automatic div to expand to the set element

I have a problem.
How to make a div expand to the end of a positional element.

.apple {
  background: #ccc;
  width: auto;
}
<div class="apple">
  A for aplle
  <br><a style="position:relative; top:20px;">B for Ball</a>
</div>
Run codeHide result

Here the div does not accept the width of the positioned element. How to make it work. Thank.

+4
source share
3 answers

He does what he must. You position the element 20px below, where it naturally falls into the DOM, so it fits outside the gray div. I understand that your situation may be more complicated. Can you do something like add padding-bottom:20px?

.apple {
  background: #ccc;
  width: auto;
  padding-bottom: 20px;
}
<div class="apple">
  A for aplle
  <br><a style="position:relative; top:20px;">B for Ball</a>
</div>
Run codeHide result
+2
source

Try adding display: table;to the parent and display: table-row;to the child.

.apple {
  background: #ccc;
  width: auto;
  display: table;
}
.apple a {
  display: table-row;
}
<div class="apple">
  A for aplle
  <br><a style="position:relative; top:20px;">B for Ball</a>
</div>
Run codeHide result
0

position: relativemoves the element to its original position (if there is an upper, lower, right or left setting), but at the same time saves the space that it originally had in the original (not moved) position that you see in your example. It does NOT resize the parent element as opposed to positioning static.

To solve the problem, you can make a tag aa inline-block, erase relative positioning and use margin-topinstead top. This will be completed by the parent:

.apple {
  background: #ccc;
  width: auto;
}
<div class="apple">
  A for aplle
  <br><a style="display: inline-block; margin-top:20px;">B for Ball</a>
</div>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1673726/


All Articles