Home > Enterprise >  Why do I cannot center elements if i scale them
Why do I cannot center elements if i scale them

Time:11-06

I am using this to center things in CSS:

.testclass {
display: flex;
justify-content: center;
}

but when i want to scale elements using width and height, it doesn't work and my elements are not centered.

Like this:

.testclass {
display: flex;
justify-content: center;
width: 200px;
height: 200px;
}

What's the problem?

CodePudding user response:

This looks like the expected behavior.

Remember that in this case justify-content: center; centers what is inside the container - not the container itself.

EDIT: I added margin: 0 auto; to center the container.

#container1 {
  display: flex;
  justify-content: center;
  border: 1px solid red;
}

#container1 > div {
  border: 1px solid blue;
  background: yellow;
}

#container2 {
  display: flex;
  justify-content: center;
  border: 1px solid red;
  width: 200px;
  height: 200px;
  margin: 0 auto;
}

#container2 > div {
  border: 1px solid blue;
  background: yellow;
}
<div id="container1">
  <div>test 1</div>
</div>
<div id="container2">
  <div>test 2</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

display: flex; and justify-content: center; works for parent elements. That is, child elements of that particular parent will be centered, not the parent.

To center .testclass

HTML

<div class="parent">
    <div class="testclass"></div>
</div>

CSS

.parent {
    background-color: red;
    display: flex;
    justify-content: center;
 }
 .testclass {
    background-color: green;
    width: 200px;
    height: 200px;
 }

    

CodePudding user response:

If you want full center (horizontal vertical) you can use this code:

.container {
  position: relative;
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="container">
  <div class="testclass">Content</div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related