0

enter image description here

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Grid</title>
    <style>
        *{
            box-sizing: border-box;
        }
        .container{
            border: 2px solid brown;
            display: grid;
            grid-template-columns: 400px 300px;
            grid-template-rows: 150px 250px auto;
        }
        .item{
          border: 2px solid black;
          margin: 5px;
          height: 100px;
          width: 100px;
          background-color: yellow;
        }
        .item1{

        }
        .item2{

        }
        .item3{

        }
        .item4{

        }
        .item5{

        }
    </style>
</head>
<body>
    <div class="container">
        <div class="item item1">1</div>
        <div class="item item2">2</div>
        <div class="item item3">3</div>
        <div class="item item4">4</div>
        <div class="item item5">5</div>
    </div>
</body>
</html>

As you can see from the code, I haven't given any width for the div.container element, so it should take the width as per the total width of the columns which should be 700px (400px+300px). So why does my container take more width than that as it is shown on the image?

2
  • Why do you assume the div container would be only 700px wide. It will be 100% wide by default. Commented May 17 at 17:20
  • @Paulie_D Oh right block elements will take the full width my bad.Thanx Commented May 17 at 17:24

1 Answer 1

0

Block elements like a div always stretch to 100% width of their parent, unless configured otherwise.

Set width: min-content; on the .container, so it would be as wide as the columns.

* {
  box-sizing: border-box;
}

.container {
  width: min-content;

  border: 2px solid brown;
  display: grid;
  grid-template-columns: 400px 300px;
  grid-template-rows: 150px 250px auto;
}

.item {
  border: 2px solid black;
  margin: 5px;
  height: 100px;
  width: 100px;
  background-color: yellow;
}
<div class="container">
  <div class="item item1">1</div>
  <div class="item item2">2</div>
  <div class="item item3">3</div>
  <div class="item item4">4</div>
  <div class="item item5">5</div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.