Home > Net >  box-siszing: border box and height
box-siszing: border box and height

Time:12-01

I am trying a simple border box here that does not seems to work for the height of my box

* {
    box-sizing: border-box;
}

.div1 {
    width: 500px;
    height: 200px;
    border: 5px solid #E18728;
    float: left;
}

.div2 {
    width: 90%;
    height: 90%;
    padding: 20%;
    border: 4px solid black;
}
<!DOCTYPE html>
<html lang="fr">

<head>
    <link rel="stylesheet" type="text/css" href="style2.css">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="div1">
        <p>This is the parent! </p>
        <div class="div2">
            <p>This is the child</p>
        </div>
    </div>

</body>

</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

What seems to be the problem ? Width is okay, inside the box however height is not. Why ? I am completely new to CSS and hope your answers will help me and others: I have found no solutions on the web. Thank you from France

CodePudding user response:

its your p tag as well as your padding:

* {
    box-sizing: border-box;
}

.div1 {
    width: 500px;
    height: 200px;
    border: 5px solid #E18728;
    float: left;
}

.div2 {
    width: 90%;
    height: 90%;
    border: 4px solid black;
}
<!DOCTYPE html>
<html lang="fr">

<head>
    <link rel="stylesheet" type="text/css" href="style2.css">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="div1">

        <div class="div2">
      
        </div>
    </div>

</body>

</html>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The problem is on the padding of the second div...

As stated here: MDN Web Docs - Padding

if you put the padding as a percentage (20%) then it refers to the width of the containing block. So, in your code, the padding you are applying a padding of 200*20/100 = 100px and that's forcing your div2 to grow to accomodate the paragraph inside.

Remove the padding or express it in absolute units and you're done!

  • Related