title: Absolute position element centered as long as it fits on the screen
body: <p>I am creating a tooltip system using only CSS that displays tooltips absolute centered below the element you can hover over to see the tooltip. Tooltips must have a minimum width. In my example below, you will see this works fine on the second element. On the first though, the tooltip does not fit on the screen and will be cut off. In this scenario (the tooltip not fitting on screen on the left side) it should just left align. If it were on the right side of the screen, it should align right. I might be pushing the CSS boundaries, but might there be a CSS solution?</p>
  <p><strong>Edit:</strong> as others have pointed out, this cannot be done purely in CSS. JavaScript can be used with <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect" rel="nofollow noreferrer">Element.getBoundingClientRect()</a>. Of course, there are also pre-made solutions such as <a href="https://popper.js.org/" rel="nofollow noreferrer">PopperJS</a>.</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-css lang-css prettyprint-override"><code>[data-tooltip] {
    padding: 3px 6px;
    color: white;
    background: red;
    position: relative;
    margin: 3px;
  }
  
  [data-tooltip]::after {
    content: attr(data-tooltip);
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    margin: 2em auto;
    opacity: 0;
    pointer-events: none;
    transition: all 0.4s ease-in-out;
    padding: 10px;
    color: #fff;
    background: darkgray;
    min-width: 100px;
    box-shadow: 2px 2px 1px silver;
  }
  
  [data-tooltip]:hover::after {
    opacity: 1;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="padding: 10px 0px"&gt;
    &lt;span data-tooltip="This text (or element) will be cut off somewhat on the left side"&gt;Hover me
    &lt;/span&gt;
    &lt;span data-tooltip="This tooltip will be completely shown because it is not near any edge"&gt;Second one
    &lt;/span&gt;
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>