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?
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
}
top:50%;
for vertical and left:50%;
for horizontal.translateY(-50%)
for vertical and translateX(-50%)
for horizontal centering.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.