Home > Blockchain >  CSS for placing divs in the middle of a screen centered div and the edge of the screen
CSS for placing divs in the middle of a screen centered div and the edge of the screen

Time:11-02

Here is the code:

body {
  position: relative;
  font-size: 30px;
}

#middle {
  width: 420px;
  height: 500px;
  margin: 100px auto 0;
  border: solid;
}

#left {
  position: fixed;
  border-style: solid;
  border-color: red;
  top: 50%;
  transform: translateY(-50%);
  left: 0;
}

#right {
  position: fixed;
  border-style: solid;
  border-color: blue;
  top: 50%;
  transform: translateY(-50%);
  right: 0;
}
<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html charset=utf-8" />
  <title>Centered divs</title>
</head>

<body>

  <div id="left"></div>

  <div id="middle"></div>

  <div id="right"></div>
</body>

</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

How should the CSS code get modified in order for the two divs with ids left and right to get centered between the div in the middle and their respective edges of the screen? (Till now I have succeeded in centering the divs vertically and placing them on both sides of the central div, but not in centering them horizontally within the space of the central div and the screen edges.)

CodePudding user response:

since the middle div has a fixed width you can use some math:

body {
  font-size: 30px;
}

#middle {
  width: 420px;
  height: 500px;
  margin: 100px auto 0;
  border: solid;
}

#left {
  position: fixed;
  border: solid red;
  top: 50%;
  transform: translate(-50%,-50%); /* updated this too */
  left: calc((100% - 420px)/4); /* half of (half the remaining space) */
}

#right {
  position: fixed;
  border: solid blue;
  top: 50%;
  transform: translate(50%,-50%);
  right: calc((100% - 420px)/4);
}

* {
  box-sizing:border-box;
}
<div id="left"></div>
<div id="middle"></div>
<div id="right"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

the best way to do this is to use flexbox

body {
  
  font-size: 30px;
}
#container{
display:flex;
justify-content:space-between;
align-items:center;
}
#middle {
  width: 420px;
  height: 500px;
  
  border: solid;
}

#left {
 
  border-style: solid;
  border-color: red;
  display:inline;
  
  
}

#right {
 
  border-style: solid;
  border-color: blue;
  display:inline;
  
}
<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html charset=utf-8" />
  <title>Centered divs</title>
</head>

<body>
<div id='container'>

  <span id="left"></span>

  <div id="middle"></div>

  <div id="right"></div>
  </div>
</body>

</html>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related