Home > Software engineering >  How to decrease width of the box from both right and left equally when the containing block size cha
How to decrease width of the box from both right and left equally when the containing block size cha

Time:03-31

I have made a bordered box. Here is the css code:

.Box{
  height: 500px;
  width: 700px;
  border: 2px solid black;
  margin: auto;
  margin-top: 10px;
 
  
}

When I run the following CSS my box appears as shown in the image below.

enter image description here

Now when I try to decrease the size of the containing block of the box, till there is a margin on both sides the box remains in the middle and the margins decrease but once the margin space is over the left border becomes stationary and only the right portion starts to shrink.

enter image description here

In the above image, it could be seen that the margin has fully shrunken and now the left side is stationary and the right side is only shrinking

I want the box to shrink from both sides equally even when the margin is over. Please guide me on how I could achieve this. Please let me know if more information is required.

CodePudding user response:

You can use the CSS function min to make sure the box is 700pa when its container has a width greater than or equal to 700px, and thereafter it will take on the width of the container.

This snipper transitions the container width from 100vw to 100px (and vice versa) when you click the button. It has a backgound color so you can see when it is larger than the box.

body {
  width: 100vw;
}
.container {
  width: 100vw;
  transition: width 5s linear;
  margin: 0 auto;
  background-color: #eeeeee;
}
.container.shrink {
  width: 100px;
}
.Box{
  height: 500px;
  width: min(700px, 100%);
  border: 2px solid black;
  margin: auto;
  margin-top: 10px;  
}
<button onclick="document.querySelector('.container').classList.toggle('shrink');">Click me to make the container shrink/grow</button>
<div >
<div ></div>
</div>

CodePudding user response:

In your approach if you change your width:700px; to max-width:700px; when screen shrinks, both left and right borders will shrink with them because when the screen width is smaller your box's width will be equal to screen width.

.Box{
  height: 500px;
  max-width: 700px;
  border: 5px solid red;
  margin: auto;
  margin-top: 10px;
}

body {
  min-height: 100vh;
  margin:0;
}

.container {
  height: 500px;
  max-width: 700px;
  border: 5px solid red;
  margin: auto;
  margin-top: 10px;
}
<div ></div>

  •  Tags:  
  • css
  • Related