Reputation: 34519
I've been trying to fix this layout problem for an hour or so with no luck. I simply want my li
to expand to match the height of its contents, so that margin-bottom
will work correctly. Here's my code (note: this is just a draft, so the relevant CSS is mixed in via style
attributes):
<!-- This uses ASP.NET markup syntax but should still be legible to anyone -->
<h2>Related</h2>
<ul class="list-unstyled owner-list">
@foreach (var package in Model.RecommendedPackages)
{
<li style="position: relative; word-break: break-all; height: auto;">
<a href="@Url.Package(package.Id)" title="@package.Id" target="_blank">
<img class="owner-image" aria-hidden="true" alt="" width="32" height="32"
src="@(PackageHelper.ShouldRenderUrl(package.IconUrl) ? package.IconUrl : Url.Absolute("~/Content/gallery/img/default-package-icon.svg"))"
@ViewHelpers.ImageFallback(Url.Absolute("~/Content/gallery/img/default-package-icon-256x256.png"))
/>
</a>
<div style="display: inline-block; position: absolute;">
<a href="@Url.Package(package.Id)" title="@package.Id" target="_blank" style="word-wrap: break-word;">@package.Id</a>
</div>
</li>
}
</ul>
Here are the results:
Here are the dimensions of the div
inside the li
:
Here are the dimensions of the li
, which is clearly shorter than its child div
:
I tried using height: auto;
to fix this (as you can see in the picture) but it didn't work. Am I doing anything wrong?
Upvotes: 1
Views: 844
Reputation: 904
It's because you have an absolutely positioned element inside of a relatively positioned element. When you have an absolutely positioned element, it doesn't take up any visual space inside the containing non-statically positioned element.
An absolute element is an element positioned relative to it's nearest non-static ancestor.
So, if you have a fixed, relative, sticky, or another absolute element ancestor (outer element), the inner element won't take up any space there.
The li element gets the 32 px height from the image inside, since li will automatically be the height of the contents, and additionally, it is explicitly (and unnecessarily) set to auto.
What you describe as the desired affect is the default. The height of the outer element will automatically fit the contents. The solution is to either put no position, and that will default or explicitly set position to a attribute that does take up space in its ancestors (static, relative, etc.).
Upvotes: 3