1

I want to make a header with a centered textbox in it but can't seem to center it. I know countless similar questions have been asked but I can't wrap my head around how I would do it with the textbox on top of the image.

Does anyone here have a solution? I prefer using flex. In the code snippet I'm trying to center the red box.

#container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  position: relative;
  background: purple;
  width: 100%;
  height: 100vh;
}
#back {
  background: blue;
  height: 80%;
  width: 80%;
}
#top {
  position: absolute;
  background: red;
  width: 40%;
  height: 40%;
  margin-left: 25%;
  margin-top: auto;
}
<div id="container">
  <div id="top"></div>
  <div id="back"></div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Emric Månsson
  • 495
  • 6
  • 15

2 Answers2

4

#container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  position: relative;
  background: purple;
  width: 100%;
  height: 100vh;
}
#back {
  background: blue;
  height: 80%;
  width: 80%;
}
#top {
  position: absolute;
  background: red;
  width: 40%;
  height: 40%;
  left: 50%;                        /* center horizontally */
  top: 50%;                         /* center vertically */
  transform: translate(-50%,-50%)   /* tweak for precise centering; details:
                                       http://stackoverflow.com/q/36817249 */
}
<div id="container">
  <div id="top"></div>
  <div id="back"></div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
2

here is another answer jsfiddle 1

#container {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    position: relative;
    background: purple;
    width: 100%;
    height: 100vh;
}

#back{
    background: blue;
    height: 80%;
    width: 80%;
}

#top {
    position: absolute;
    background: red;
    width: 40%;
    height: 40%;
    left: 0;
    right: 0;
    margin-left: auto;
    margin-right: auto;
    margin-top: 12%;
    
}
 <div id="container">
            <div id="top"></div>
            <div id="back"></div>
        </div>
David Genger
  • 875
  • 10
  • 25