I want to make my div elements be centered in the same line. I want it to be done without using a fixed margin because that doesn't work as soon as you resize it or change screen resolution.

I've tried using "margin: 0 auto" but that didn't seem to work. I've also trid a couple of different things but they were honestly all just me kicking in the dark.

The HTML:

  <div class="container div3">
    <div class="sredina">

    <div class="box">
      <img>
      <h3></h3>
      <p></p>
    </div>


    <div class="box">
      <img>
      <h3></h3>
      <p></p>
    </div>


    <div class="box">
      <img>
      <h3></h3>
      <p></p>
    </div>

</div>

The CSS:

.box{
  text-align: center;
  width: 20%;
  border: 2px solid blue;
  margin: 1pt;
  float: left;}

.div3{
  text-align: center;}

.sredina{
  display: inline-block;
  margin: auto;
  border: 2px solid red;}

.container{
  width: 80%;
  margin: auto;
  overflow: hidden;
}

How it looks now: An image of how it looks now

How I want it to look: An image of how it should look

3 Answers

1
HappyHands31 On Best Solutions

Use display: flex and justify-content: center on the the .sredina div within your container:

https://codepen.io/HappyHands31/pen/qwvEez

1
dimas On

Try to use flex for your .sredina

https://codepen.io/anon/pen/zXbxym

.sredina{
  display: flex;
  justify-content: center;
  align-items: strentch;
  margin: auto;
  border: 2px solid red;
}
0
Sivaramakrishnan On

Try this,

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .outer{
            background: #87ceeb;
            width: 100%;
            margin-left: auto;
            margin-right: auto;
            position: relative;
            text-align:center;
        }
        .inner{
            display: inline-block;
            min-height: 100px;
            height: 100px;
            background: chartreuse;
        }
    </style>
</head>
<body>
    <div class="outer">
        <div class="inner">hello</div>
        <div class="inner">hello</div>
        <div class="inner">hello</div>
    </div>
</body>
</html>

it works well in all screen sizes. You must use

display: inline-block;

in the inner div class

then use

margin-left: auto;
margin-right: auto;
position: relative;
text-align:center;

in the outer div.

A similar answer is here