1

inline-block elements using overflow: hidden position themselves so their bottom margin is the baseline. From http://www.w3.org/TR/CSS2/visudet.html#leading:

The baseline of an 'inline-block' is the baseline of its last line box in the normal flow, unless it has either no in-flow line boxes or if its 'overflow' property has a computed value other than 'visible', in which case the baseline is the bottom margin edge.

In practice this means these elements are shifted up unexpectedly; e.g., inside a <td> the element will not be vertically centered. A simpler example:

div {
  border: 1px solid red;
  text-decoration: underline;
}
.ib {
  display: inline-block;
}
.h {
  overflow: hidden;
}
<div>
  <div class="ib">Visible</div>ABgjh</div><br>
<div>
  <div class="ib h">Hidden</div>ABgjh</div>

the div with overflow: hidden doesn't share the same baseline as its surrounding line.

I'm looking for a simple way to make that div align itself as if it was following the normal rules for inline-block elements. Basically I want to write a custom element that "just works" whether its consumer applies a vertical-align style, or places it inside a <td>, etc.

This table has an example where I want the element to vertically center itself but instead it pushes itself up (and the rest of the line down).

This fiddle has more examples showing how different pairings of vertical-align behave unexpectedly when one element is display: inline-block; overflow: hidden.

To be clear, this question is asking whether a <div style="overflow: hidden"> can be wrapped in such a way that it can be treated as a regular inline-block element, positioning itself intelligently, without JS or font-based pixel adjustments. I'd want to be able to apply styling to the final component in order to position or align it as I please, as if it were a regular inline-block element.

mgiuffrida
  • 3,299
  • 1
  • 26
  • 27

1 Answers1

0

I am not sure what browsers you are looking to support but if you wrap your DIV with display: flex; you wont get that vertical offset. You can see it here:

    div {
      border: 1px solid red;
      text-decoration: underline;
    }
    .ib {
      display: inline-block;
    }
    .h {
      overflow: hidden;
    }
    .flex {
      display: flex;
    }
<div>
  <div class="ib">Visible</div>
  ABgjh
</div>
<div class="flex">
  <div class="ib h">Hidden</div>
  ABgjh
</div>

I normally don't use flexbox because of the lack of browser support but perhaps this is the simple solution you're looking for. Hope that helps.

crazymatt
  • 3,266
  • 1
  • 25
  • 41
  • I'd still like the div to behave as inline-block; wrapping with flex (or inline-flex) causes different behavior. Try, for example, inserting a `
    ` within the "ABgjh" text. FWIW, I'm only using this for Chrome UI, so a Chrome-specific solution is fine.
    – mgiuffrida Mar 04 '15 at 01:30