css child padding makes it draw out side the parent

后端 未结 5 926
醉话见心
醉话见心 2020-12-23 21:19

Applying padding to child elements is making the child draw over the boundaries of its containing parent. Can you please explain the size consideration in margin,padding an

相关标签:
5条回答
  • 2020-12-23 21:25

    You must do add display: block; to <a> element to expand parent as you need. See this fiddle

    0 讨论(0)
  • 2020-12-23 21:31

    Can be solved without making any change in a tag. Just add overflow: hidden; property to div element.

    div {
      margin-top:90px;
      margin-left:90px;
      background-color:#676896;
      overflow: hidden; /*expends its height if not fixed*/
    }
    

    Updated fiddle here: http://jsfiddle.net/NkXUW/52/

    0 讨论(0)
  • 2020-12-23 21:33

    the reason the child was overdrawing the boundaries of the parent is because the child is a tag of type <a> which by default is display:inline (you can see if that you go in chrome developer tools and see under computed style). an inline element displays like a line of text.. so the way it treats width and height and all that is very different than a block (a div for example is a block by default).

    that being said, if you change the display setting of a to display:inline-block you get to keep the inline properties of <a> but at the same time also get the block properties, namely having a padding and width and height that is recognised by its parent node, which will then expand to accommodate it.

    So there aren't any best practices about this. The only best practice is to understand what each display property mean (ie inline vs block vs inline-block) and put it to its proper use.

    0 讨论(0)
  • 2020-12-23 21:44

    about different between margin and padding please read this maybe it help you

    I don't think this is correct float your div wrapper

    working demo

    div {
        float:left;
        margin-top:90px;
        margin-left:90px;
        background-color:#676896;
    }
    

    hope this help you..

    0 讨论(0)
  • 2020-12-23 21:46

    Use display:inline-block;

    a {
        background-color: #C34567;
        display: inline-block;
        padding: 10px;
    }
    

    SEE DEMO

    • An inline element has no line break before or after it, and it tolerates HTML elements next to it.
    • A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.
    • An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.

    http://www.w3schools.com/cssref/pr_class_display.asp

    0 讨论(0)
提交回复
热议问题