using element's own (not parent's) width for calculation or percentage in css, without javascript

Brian J. Fink picture Brian J. Fink · Feb 7, 2014 · Viewed 32.7k times · Source

I've been experimenting with a way to get a page element to overlap the elements on either side of it and stay perfectly centered between them. My solution was to declare position:relative and set negative margin values roughly equal to 50% of the element's width, but the closest I've been able to come is to half the element's percentage of its parent's width:

<!DOCTYPE html>
<html>
 <head>
  <style>
  .clap {
   position:relative;
   margin:auto -16.66%; // This element's share of the entire parent's width = 33.33%
   color:#f00
  }
  </style>
 </head>
 <body>
  <center>
   <span style="display:inline-block">1234567890<span class="clap">1234567890</span>1234567890</span>
  </center>
 </body>
</html>

I'm trying to find a CSS-only solution that will use the width of the element itself, not the width of the container. I can't use JavaScript to do this because I plan to use it as a MathJaX fix by embedding it in a \style command. (As far as I know, MathJaX does not provide for embedded HTML or JavaScript code within its formulas, so you see why this must be CSS-only. I know it's possible with scripting. Is it possible with CSS, or is my endeavor hopeless?

Update: Thanks to a suggestion from @Daiwei, I think I'm on the road to the right solution. Thanks for all your answers. Here is the revised code:

.clap {
 position:absolute;
 display:inline-block;
 transform: translate(-50%,0);
 color:#f00                      // for contrast 
}

I'd love to show you the results, but I can't upload a picture. Sorry.

Another update: The solution I presented above works best in an HTML/CSS context, but it breaks in a MathJaX array, matrix, or similar tabular environment. Specifically, if the element is too long, it clips on the left side. Relative positioning moves the element halfway to the left but leaves a gaping space where it used to be! Any ideas for patching it up?

Answer

Jason Lydon picture Jason Lydon · Jun 23, 2015

I've seen a modern trick to center elements using transform. (If I am understanding the underlying question)

element {
  position:relative;
  top:50%; // ^1
  transform:translateY(-50%); // ^2,3
}
  1. You can use top:50%; for vertical and left:50%; for horizontal.
  2. You would then use translateY(-50%) for vertical and translateX(-50%) for horizontal centering.
  3. You need to use prefixes for transform. I highly recommend autoprefixer in your workflow.

Bonus:
You can also use this trick to align elements to the bottom or right of it's parent, like in a table-cell by using 100% instead of 50% in the css.