-3

I'm in a course where I should complete a challenge only using padding and margin

the current challenge is to center a div element with a border that is inside the body with the width: 200px and padding: 50px inside to make it easier to see and look (padding is not necessary)

I used this code to center it horizontally but for vertically I have no idea

div {
  width: 200px;
  border: 4px solid black;
  padding: 50px;
  margin: auto;
}
<body>
  <div></div>
</body>

Help me center it vertically as well but no flex box and position & transform

Am.Shekari
  • 107
  • 5
  • 1
    Hi, I think some of the context has been lost in an edit (maybe by @AhmadHabib) Your original question had the full document, including the body, and this might be important for an answer as the height of body is important (however it can be calculated or forced). – A Haworth Jul 13 '22 at 11:16

2 Answers2

3

You can use CSS calc - this snippet assumes that the body is 100vh height in the absence of further information.

You can work out what space is not being taken up by the div and the halve it and use it to calculate a top margin. The space taken up is 2*border width + 2 * padding

div {
  width: 200px;
  border: 4px solid black;
  padding: 50px;
  margin: auto;
  margin-top: calc( (100vh - 100px - 8px) / 2);
}
<body>
  <div></div>
</body>
Am.Shekari
  • 107
  • 5
A Haworth
  • 30,908
  • 4
  • 11
  • 14
  • Thanks it was good but it is possible to not use calc? – Am.Shekari Jul 13 '22 at 10:48
  • Hi, is there a problem with using calc? The question seemed to imply only margin and padding CSS properties could be used but didnt say anything about restricting what could be used for values. – A Haworth Jul 13 '22 at 10:52
  • Not a single problem and its accepted as well I was just looking to see is it possible to do it as simple as centering it horizontally – Am.Shekari Jul 13 '22 at 10:53
  • @AHaworth How about you stop posting general answers and actually explain what calc does and why it should be used when you suggest it. Linking a credible source that further explains calc and the compatibility would also be preferred. – O'con Jan 10 '23 at 22:46
0
 div {
        width: 200px;
        border: 4px solid black;
        overflow: auto;
        margin: auto;
        position: absolute;
        top: 0; left: 0; bottom: 0; right: 0;
              
    
}