I can not set margin-top / bottom / right for block element, why?

6

I have a <p> element inside a <div> , like this:

HTML

<div>
    <p>texto</p>
</div>

CSS

div {
  width: 30px;
  height:30px;
  background-color: green;
}

p {
  width: 30px;
  height:30px;
  background-color: red;
  margin: 10px 10px 10px 10px;
}
When I apply margin-left it works normally, the element <p> gets away 10px from the left, however when I apply margin-top , margin-bottom or margin-right nothing is changed, <p> element remains in the same position. I do not understand why, does anyone know how to explain this behavior?

View example in JSBin

    
asked by anonymous 28.01.2014 / 22:06

2 answers

8

We have a big problem there. The two elements have the same dimensions and you are trying to gain more space.

The margin of p is out of div , as you can see using a web inspector:

Lookingatthepositionofp,itiscomingoutofdiv:

For this to work in this way, you would need a overflow: hidden in div (to prevent margin collapse) and 50px height and width (% with% of dimensions + 30px margin , 20px on each side).

<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8 />
</head>
<body>
  <div><p></p></div>
</body>
</html>
div {
  width: 50px;
  height: 50px;
  background-color: green;
  overflow: hidden;
}

p {
  width: 30px;
  height:30px;
  margin: 10px;
  background-color: red;
}

link

Consider using 10px on padding instead of div on margin . And, depending on the content, using p on both elements may be more useful.

    
29.01.2014 / 04:20
3

The upper margin is yes being applied, the problem is that it collapses with the edge of the outer div, and ends up being applied between the outer div and the top of the page.

You can see a detailed description of how this works in this my other answer , but the explanation well summed up in this case is this: when you have several nested blocks, and only the inner one has a higher margin, that margin ends up collapsing with that of the ancestral blocks , and ends applied between the outermost and its parent (here, the body).

As this only happens with blocks, the simplest solution is to turn your paragraph into a inline-block :

p {
  width: 30px;
  height:30px;
  background-color: red;
  margin: 10px 10px 10px 10px;
  display: inline-block;
}

Demo on jsbin

    
28.01.2014 / 22:21