-2

I use margin: 0px auto; in display : inline-block but my element is unable to comes in center but when i use display : block it comes in center.

.container {
  background-color: beige;
  border: 1px solid red;
  width: 250px;
  height: 200px;
  display: inline-block;
  margin: 0px auto;
}
<div class="container">
  This is Container
</div>
Kunal Tanwar
  • 1,209
  • 1
  • 8
  • 23

3 Answers3

1

display: inline-block will make the container to flow on the way as the same way as inline elements like span flows. To center as inline-block container you have to provide text-align: center to parent container.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS TUTORIAL - Border</title>

  <style>
    body {
      text-align: center;
    }
    
    .container {
      background-color: beige;
      border: 1px solid red;
      width: 250px;
      height: 200px;
      display: inline-block;
    }
  </style>

</head>

<body>
  <div class="container">
    This is Container
  </div>

</body>

</html>
Sachin Som
  • 1,005
  • 3
  • 8
1

Can you try to add this style to body class

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS TUTORIAL - Border</title>

    <style>
      body {
      text-align: center;
    }
    
    .container {
      background-color: beige;
      border: 1px solid red;
      width: 250px;
      height: 200px;
      display: inline-block;
    }
    </style>

</head>
<body>
    <div class="container" >
          This is Container
    </div>

</body>
</html>
text-align:center;
1

why is working with block?

If you use display: block will be taking 100% of the space and then center it auto.

enter image description here

like you see in the image before there is that orange color (space) because it takes up 100% of space.

why is NOT working with inline-block?

an inline element takes less space, so technically the auto value will be set to 0

enter image description here


how to center:
follow the other answer for how to center with:
flex or grid: @kunal's answer
or text-align: @ardan's answer

I tried to tell you why is not working :)

Laaouatni Anas
  • 4,199
  • 2
  • 7
  • 26