3

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;
}
Allen
  • 478
  • 9
  • 21
  • 1
    Is there a place to discuss the moderation on this question? It was closed for being a duplicate, but is not. The accepted answer in the associated question explicitly violates the conditions in this question. – Allen Sep 06 '20 at 20:06
  • 1
    You're right to be frustrated, @Allen. Unfortunately, sometimes it feels like there are over-eager moderators all over Stack Overflow who don't read a question properly and then mark the question (incorrectly) as a duplicate. It is a perennial problem that appears to be baked in to Stack Overflow. I have voted to reopen and someone else has too. When enough people vote to reopen your question, then the false dupe will go away. – Rounin Sep 06 '20 at 21:08

1 Answers1

1

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?

koder613
  • 1,486
  • 5
  • 21