4

I want to position a <div class="container"></div> in the middle of the screen in such a way so that it's responsive to any screen size. The red marked area on the screenshot should always appear in the middle of the screen.

How to position it? Currently I'm using margin-top:85px when I squeeze the browser, the distance between the red marked area and the navbar should decrease as well.

enter image description here

halfer
  • 19,824
  • 17
  • 99
  • 186
Noob Coder
  • 2,816
  • 8
  • 36
  • 61
  • when you say in the middle of the screen, your container should be in the middle horizontally ? – Arkantos Jan 10 '16 at 14:36
  • nope.. it should appear in the middle only for the md and lg screen size. for the xs and sm devices the input fields and the login button goes under the texts@arkantos – Noob Coder Jan 10 '16 at 14:43

5 Answers5

2

Working code snippet has been added. This code will centre your div both horizontally and vertically for any screen size.

Set the css property position:relative for parent of the container.

.container {
  width: 400px;
  height: 300px;
  background-color: #ccc;
  position: absolute;
  /*it can be fixed too*/
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  /*this to solve "the content will not be cut when the window is smaller than the content": */
  max-width: 100%;
  max-height: 100%;
  overflow: auto;
}
<div class="container">
</div>
Sooraj
  • 9,717
  • 9
  • 64
  • 99
2

Have you tried absolute centering? You would need to add a position relative to the parent container... You would also need to declare a height on the container element...

.parent-container {
    position: relative;
}

.container {
    width: 50%;
    height: 50%;
    overflow: auto;
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
}

I hope this helps...

steffcarrington
  • 404
  • 3
  • 13
0

Define some width on your container and set margin top & bottom to some desired value and left & right values to auto so that it will always split the remaining space on the both sides equally.

.container{
  width : 84%
  margin : 2rem auto;
}
Arkantos
  • 6,530
  • 2
  • 16
  • 36
  • thats only centering it horizontaly, also only if the parentelement is configuered correctly, please improve your answer – CoderPi Jan 10 '16 at 14:33
0

Try with this example

.container {
   width: 75%;
   margin: 50px auto 0;
}
Manudog
  • 159
  • 10
0

Use this in your container class

.container{
    position:fixed; 
    top:0;
    left:0;
    right:0; 
    bottom:0; 
    width:auto; 
    height:200px; /****set height****/
    margin:auto;
}

It will work

LOTUSMS
  • 10,317
  • 15
  • 71
  • 140
Head In Cloud
  • 2,001
  • 1
  • 8
  • 10