4

How can I achieve something like this? #find must be vertically and horizontally centered.

enter image description here

Here is my code

#main {
    min-height: 50vh;
    display: flex;
    justify-content: center;
}
#menu {
    padding: 20px 0px;
    font-size: 1em;
}
#find {
    width: 310px;
    min-height: 320px;
    position: relative;
}

More code is here

Sevle
  • 3,109
  • 2
  • 19
  • 31
Karolina Ticha
  • 531
  • 4
  • 19

2 Answers2

1

To do this you can use flexbox with position: absolute: on #menu like this

#main {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #B8E986;
  justify-content: center;
  position: relative;
}

#menu {
  padding: 20px 0px;
  font-size: 1em;
  background: #D0021B;
  width: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

#find {
  width: 50px;
  min-height: 50px;
  background: #F5A623;
}
<div id="main">
  <div id="menu">
    Menu div
  </div>
  <div id="find">
    Find div
  </div>
</div>

Or you could create another child div and set display: flexbox; to parent.

#main {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #B8E986;
}

#menu {
  padding: 20px 0px;
  font-size: 1em;
  background: #D0021B;
  width: 100%;
}

#find {
  display: flex;
  justify-content: center;
  flex-direction: column;
  flex: 1;
}

.center {
  width: 50px;
  min-height: 50px;
  background: #F5A623;
}
<div id="main">
  <div id="menu">
    Menu div
  </div>
  <div id="find">
    <div class="center">
      FInd div
    </div>
  </div>
</div>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

Flexbox has made setting margin to auto a whole lot more powerful. Doing so along the flex axis now takes up any remaining space before dividing it up between the flex items. This is the holy grail of CSS, true vertical centering.

I often use this to push footers down to the bottom of the page when the content is not tall enough. Flex is awesome.

#main {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #B8E986;
}

#menu {
  padding: 20px 0px;
  font-size: 1em;
  background: #D0021B;
  width: 100%;
}

#find {
  width: 50px;
  min-height: 50px;
  background: #F5A623;
  
  margin-top: auto;
  margin-bottom: auto;
}
<div id="main">
  <div id="menu">
    Menu div
  </div>
  <div id="find">
    Find div
  </div>
</div>
Huba Nagy
  • 408
  • 3
  • 7