top moves parent element

I have a code like this:

<html>
<head>
....
</head>
<body>
   <div class="custom">
      ...custom stuff here...
   </div>
</body>

Next I have a css like this :

.custom{
margin-left: 45%;
margin-top: 45%;
}

This code is supposed to move the div always to center of the screen. The margin left works perfectly fine, and centers the div properly, but the margin-top moves the body element - which is the parent element of the div. If I change the units to other than % (px,em,rem) it works fine ... but with % it moves the body. I tried stuff like adding little padding/margin to parent, adding overflow and other properties inside the parent but it is still doing the same thing. The body element is moved by 45% to almost double size of my screen, so in the end the is almost out of the screen at the bottom.

If the margin should not accept % units why is the margin-left working fine ? I don't understand this behaviour. Also elements inside div should absolutely not do anything with the parent so I am really confused right now.. Any ideas ?

Forgot to add some body definitions :

body{
   width: 700px;
   height: 400px;
   margin : 5px 5px 5px 5px;
   overflow: hidden;
   backgrou....
}

Explanation

Yes, it is a correct behaviour because the percents consider parents position. Like in your example, it will be positioned 45% below of body position.

But in your example, this wont work because 45% is not the center of any screen, see your example with some borders to see the behaviour:

body {
  border:1px solid red;
}

.custom{

  margin-left: 45%;
  margin-top: 45%;
  
  border:1px solid blue;
  
}
<div class="custom">
      ...custom stuff here...
   </div>

You are using margins, incorrectly.

Make .content absolute then place where ever you want.

see fiddle: https://jsfiddle.net/4p18mxg9/6/

.custom{
position: absolute;    
left: 45%;
top: 45%;
}

I get why you do not understand this behavior, it is a common question and a dilemma that keeps on showing up for everyone.

Before we dive into it, please reference this great article.

So, because you are trying to center your custom div using margins alone, you are essentially not centering with respect to the page. Think about what margin does for you: it clears an area around an element. You could easily have a case where your margin is equal to the greater of the adjoining margins; this is common when working with vertical margins.

You can get around this issue in different ways, namely your approach is incorrect.

I suggest looking up the article I linked and using their solution for centering things horizontally:

margin: 0 auto;

Here you may add a vertical margin if you wish like so:

margin: 20vh auto 0 auto;

Let me know if you need any more assistance

链接地址: http://www.djcxy.com/p/87778.html

上一篇: 为div添加边距不会移动背景的位置

下一篇: 顶部移动父元素