I can’t define margin-top/bottom/right for block element, why?

Asked

Viewed 2,482 times

6

I have an element <p> within a <div>, thus:

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 works normally, the element <p> distance 10px on the left, but when I apply margin-top, margin-bottom or margin-right nothing is changed, the <p> remains in the same position. I don’t understand why, someone can explain this behavior ?

View example in Jsbin

2 answers

8


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

To margin of p is out of div, how it is possible to see using a web inspector:

Margem em laranja

Looking at the position of p, he’s coming out of the div:

Sobreposição

For it to work that way, I’d need a overflow: hidden in div (to prevent the margin collapsing) and of 50px high and wide (30px of dimensions + 20px de margin, 10px 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;
}

http://jsbin.com/IXInADEg/1/edit

Consider using padding in div in place of margin in the p. And, depending on the content, use inline-block in both elements may be more useful.

  • Thank you very much ! Doubt clarified.

3

The upper margin is being applied, the problem is that it collapses with the margin of the external div, and ends up being applied between the external 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 summarized in this case is the following: when you have several nested blocks, and only the innermost has upper margin, this margin ends up collapsing with that of the ancestral blocks, and ends applied between the outermost and your father (here, the body).

Since 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 no jsbin

  • Another simple way to fix the problem is overflow:Hidden.

  • Cleiton, I ran a test with overflow:hidden, but did not resolve.

  • 1

    Bfavaretto, here is an example: http://jsfiddle.net/rLk36/.

  • @Cleiton Ah, is that the external div of the question has fixed dimensions. There the overflow:Hidden cuts the content.

  • Thank you @bfavaretto! Really, your reply with the citation of the documentation has clarified many of my doubts (:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.