How to center an element and position elements to either side

Viewed 211

I want to horizontally center an element and position elements to either side of it (but not have them part of the centering calculation). I would prefer a straight CSS solution; preferably no scripting unless super lightweight.

This is as close as I've gotten so far: https://jsfiddle.net/stupid_genius/5c0xnqmb/5/

The "Left" and "Right" elements should touch the left and right sides of the centered "X" element without altering it's position. Is there a way to do this?

Mock up of desired result: https://jsfiddle.net/stupid_genius/5c0xnqmb/3/

html, body {
    margin: 0;
    padding: 0;
}

#main {
    position: absolute;
    width: 100%;
    height: 100%;
    background: lightblue;
}

#centered {
    position: relative;
    margin: 0 auto;
    width: 500px;
    background: yellow;
}

#center {
    margin: 0 auto;
    width: 100px;
    text-align: center;
    background: gray;
}

#left,
#right {
    position: absolute;
    top: 0;
}

#left {
    /* right: calc(50% + 50px); */
    left: 0;
    width: 50px;
    background-color: green;
}

#right {
    /* left: calc(50% + 50px); */
    right: 0;
    width: 200px;
    background-color: red;
}
1 Answers

HTML:

<div id="main">
    <div id="centered">
        <div id="left">Left</div>
        <div id="center">&lt;---X---&gt;</div>
        <div id="right">Right</div>
    </div>
</div>

CSS

html, body{
    margin: 0;
    padding: 0;
}

#centered{
  display: flex;
}
#left{
  background: green;
  flex-grow: 1;
}
#center{
  margin: 0 auto;
  background: yellow;
}
#right{
  background: pink;
  flex-grow: 1;
}

See this JSFiddle.

Is this what you required?

Related