0

I have this code:

<div class='block'>
  <div class='container'></div>
</div>

.block {
  display: block;
  height: 100px;
  width: 100px;
  background: black;
}
.container {
  display: block;
  width: 30px;
  height: 30px;
  background: red;
  margin: 50px;
}

I can not understand why margin does not work inside the block?

JsFiddle: https://jsfiddle.net/39yy7a0q/

pgrekovich
  • 137
  • 1
  • 9
  • 2
    The margin is working, but you are experimenting with margin-collapse function of CSS. You can solve this kind of problems defining a border or a padding. See this fiddle: https://jsfiddle.net/39yy7a0q/7/ .block { display: block; height: 100px; width: 100px; background: black; border:1px solid black; } – Marcos Pérez Gude Oct 01 '15 at 09:06
  • https://jsfiddle.net/39yy7a0q/8/ https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing If you need cause (and you've asked 'why') - check this article.... – sinisake Oct 01 '15 at 09:07
  • You could set `.block` overflow to hidden or add a small padding. https://jsfiddle.net/39yy7a0q/10/ – orlland Oct 01 '15 at 09:12
  • The problem is your display property of container class. INLINE-BLOCK An element set to inline-block is very similar to inline in that it will set inline with the natural flow of text (on the "baseline"). The difference is that you are able to set a width and height which will be respected. DISPLAY:BLOCK They are usually container elements. Also text "blocks" like

    and

    . Block level elements do not sit inline but break past them. By default (without setting a width) they take up as much horizontal space as they can. DEMO: jsfiddle.net/39yy7a0q/11

    – Waqar Oct 01 '15 at 09:20

1 Answers1

-2

Try below css. I have added position to .container, and adjusted margin value as it should relevant to parents width. https://jsfiddle.net/39yy7a0q/4/

.block {
    display: block;
    height: 100px;
    width: 100px;
    background: black;
}

.container {
    display: block;
    position:absolute;
    width: 30px;
    height: 30px;
    background: red;
    margin: 35px;
}
Ranjana
  • 795
  • 4
  • 9
  • The problem is your display property of container class. INLINE-BLOCK *An element set to inline-block is very similar to inline in that it will set inline with the natural flow of text (on the "baseline"). The difference is that you are able to set a width and height which will be respected.* DISPLAY:BLOCK They are usually container elements. Also text "blocks" like `

    ` and `

    `. Block level elements do not sit inline but break past them. By default (without setting a width) they take up as much horizontal space as they can. DEMO: https://jsfiddle.net/39yy7a0q/11/

    – Waqar Oct 01 '15 at 09:19