no_rasora
no_rasora

Reputation: 17

How can I make multiple div elements in another div element horizontally center?

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

Upvotes: 0

Views: 53

Answers (3)

Sivaramakrishnan
Sivaramakrishnan

Reputation: 392

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

Upvotes: 0

HappyHands31
HappyHands31

Reputation: 4101

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

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

Upvotes: 1

dimas
dimas

Reputation: 389

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;
}

Upvotes: 1

Related Questions