51

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?

2
  • But if you want to make 3 elements overlap and distributed evenly, it's possible. see jsfiddle.net/g8a3Q/1 Feb 7, 2014 at 22:45
  • Why can't there just be a relative unit, el or ew, which signifies the element's width? Then I could simply refer to -.5el or something similar. IE used to have a workaround: expression(this.currentStyle.width). Feb 9, 2014 at 22:04

6 Answers 6

101

One pure CSS solution is to use transform.

element
{
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

Notes:

  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 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.
  4. If you want to support older browsers, then you'll need to use prefixes for transform. I highly recommend autoprefixer in your workflow.
0
2

And if someone (like me) was trying to center the element by its parent, use this simple style:

.clap {
 position:absolute;
 left: 50%;
 transform: translate(-50%,0);
}

0

I don't know if this is what you wanted to do, but here is a demo: http://cdpn.io/bgkDf

HTML

<div class="container">
  <div id="box-left"></div>
  <div id="box-overlap">
    <div id="box-overlap-inner"></div>
  </div>
  <div id="box-right"></div>
</div>

CSS

.container > div {
  height: 50px;
  float: left;
}
#box-left {
  width: 40%;
  background-color: red;
}
#box-right {
  width: 60%;
  background-color: green;
}
#box-overlap {
  width: 0;
}
#box-overlap-inner {
  position: relative;
  z-index: 10;
  height: 50px;
  width: 50px;
  transform: translate(-50%,0);
  background-color: rgba(0,0,255,.5);
}
8
  • this does only move the element, therefore it'll overlap on ONE side, not on both. YOu'd need to scale it to get it to overlap on both sides, and percentage values are invalid for scale(). Feb 7, 2014 at 23:20
  • I tried that in Firefox on the element in the middle. No effect. Am I doing it wrong? Feb 7, 2014 at 23:32
  • 1
    I had to add position:absolute; and display:inline-block; before transform:translate(-50%,0) worked, but I did not need scale() as @JohannesH. suggested that I would. Feb 8, 2014 at 0:07
  • @BrianJ.Fink I just updated the answer, I hope this is what you wanted to do.
    – Daiwei
    Feb 8, 2014 at 14:44
  • Thanks but your first solution was better, because it needs to work with different (not predefined) widths. And after adding the position and display, the transform worked everywhere but in a MathJaX context, which is where I was trying to use it. BTW in MathJaX I won't have the luxury of multiple containers. So I guess we misunderstood each other. Sorry if I was the one who was unclear. One clarification further: the elements I would like to overlap contain nothing but text, and have no predetermined widths. Feb 9, 2014 at 21:21
0

As the size of the element is only known after it has been styled, how should the style be able to use it? Imagine this: Some element has a width of 200% of it's own width (=double size than "normal") set in CSS. One of it's children has its width set to 100% of the parent (=our element). The default width of an element is determined by its content. Content's of our element are as width as the element itself. Our element has no width yet however, as we're waiting for it to get some default, so we can double that one. Result: Nothing will ever get any width.

Therefore: What you're trying to do is not possible. But CSS3 has its calc, maybe you can get closer to what you want to acheive using it?

1
  • 5
    I'm not attempting to change an element's width; I want to set margins based on the width. It's not an infinite loop. Feb 7, 2014 at 23:20
0

"Using element's own width for calculation or percentage" In general:

(Maybe not the best solution for your issue, but an answer to your question)

At the moment,the attr function doesn't work in Chrome. That would have been nice. But you can use variables, if you either set the parent attribute yourself, or are able to use a predefined one. That way you can use the calc() function to calculate your child attribute.

Here is an example, using the browser defined viewport size, to calculate the width of an element:

<!DOCTYPE html>
<html>
 <head>
  <style>
  :root {
     --module-size: 33vw;
   }

  .clap {
   display:inline-block;
   width: calc(var(--module-size) / 2);
   color:#f00;
   border: 1px solid;
  }
  </style>
 </head>
 <body>
  <center>
   <span style="display:inline-block">1234567890
    <span class="clap">1234567890</span>
   1234567890</span>
  </center>
 </body>

This can be used in many interesting ways, to streamline your CSS. For instance with the @media style...

0

What about converting the content to divs and enclose each within another div to use margin: auto ?

Example (each super div within its own colour and shifted a little in height for clarity):

<html>
 <head>
  <style>
    .dl 
    {
        position: absolute;
        left: 0px;  
        top: 0px;
        max-width: 50%;
        width: 50%;
        text-align: left;
        background: red;
        opacity: 0.5;
    }
    .dls
    {
        margin: auto;
    }
    .dc 
    {
        position: absolute;
        left: 25%;  
        top: 10px;
        max-width: 50%;
        width: 50%;
        text-align: center;
        background: green;
        opacity: 0.5;
        color: white;
    }
    .dcs
    {
        margin: auto;
    }
    .dr 
    {
        position: absolute;
        right: 0px; 
        top: 20px;
        max-width: 50%;
        width: 50%;     
        text-align: right;
        background: blue;
        opacity: 0.5;
        color: white;
    }
    .drs
    {
        margin: auto;
    }
    .overall-width
    {   
        position: absolute;
        left: 0%;
        width:100%;
        height: 20px;
        margin: auto;
    }
  </style>
 </head>
 <body>
    <div class="overall-width">
        <div class="dl">
                <div class="dls">
                1234567890
            </div>
        </div>
        <div class="dc">
                <div class="dcs">
                1234567890
            </div>
        </div>
        <div class="dr">
                <div class="drs">
                1234567890
            </div>
        </div>
    </div>
 </body>
</html>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.