Home > other >  How to center a parent div with flexbox
How to center a parent div with flexbox

Time:10-17

Im newbie and learning flexboxes. I can center an element which is inside of parent div but couldn't figure it out centering the PARENT DIV using flexbox.

HTML

<div class="center">
    <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. </p>
</div>
CSS
.center {
display: flex;
justify-content: center;
align-items: center;
width: 60%;
border: 5px solid #FFFF00;
padding: 10px;
}

Its working great inside the div as expected but I want the div to be centered, not inside of it. How can I do that? Note: I couldn't find the solution in the other stackoverflow questions.

Update: or what is the best solution for centering that is responsive?

CodePudding user response:

you can wrap that parent element, in another div and write that centering code on that wrapper for example like that

.wrapper{
  display: flex;
  justify-content: center;
  align-items:center;

  width: 100%;
  height: 100vh;
  border: 3px solid red
}

.box{
  width: 100px;
  height: 100px;
  background: black;
}
<div class="wrapper">
  <div class="box"><div>
<div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

remember when you want to use flex-box on element you must use always on parent element not on child

CodePudding user response:

Here is the updated code for you. CSS:

html, body {
height: 100%;
}
body {
  margin: 0;
}
.flex-container {
height: 100%;
padding: 0;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
}
.row {
width: auto;
border: 2px solid yellow;
}
.flex-item {
padding: 5px;
width: 20px;
height: 20px;
margin: 10px;
line-height: 20px;
font-weight: bold;
font-size: 2em;
text-align: center;
}

HTML:

    <div class="flex-container">
    <div class="row"> 
        <div class="flex-item">Your text here.</div>
    </div>
</div>
  • Related