Home > OS >  Responsive HTML (Resize div when window becomes smaller than div)
Responsive HTML (Resize div when window becomes smaller than div)

Time:07-26

I am curious how this type of responsive layout is achieved (see screenshots).

It looks like the form is in a div that does not start resizing or become responsive until the window has been resized smaller than the div.

I have tried a combination of divs with margins and flex, etc., and have added the <meta name="viewport" content="width=device-width, initial-scale=1.0"> tag to the head as well, but I only manage to make the page responsive to all window resizing.

Any direction here is much appreciated.maxsize maxsize-div-smaller-window div-contents-start-resizing minimum-form-size

CodePudding user response:

There are multiple methods of doing this:

@media queries:

with media queries, you can define style changes for specific breakpoints. In this case it is used to size a column to 100% width instead of 50% at screen at 480px or lower:

.container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.container > div {
  width: calc(50% - 20px);
}

@media only screen
  and (max-width: 480px) {
    .container > div {
      width: 100%;
    }
}

input {
  display: block;
  width: 100%;
  box-sizing: border-box;
}
<div >
  <div>
    <input>
    <label>Firstname</label>
  </div>
  <div>
    <input>
    <label>Lasttname</label>
  </div>
</div>

flex-grow:

This Flexbox approach defines the max-width of a column to 480px. If an element is smaller than 480px it will span the entire given width. flex-wrap: wrap is used to push the 2nd column to the next row. For screens larger than 960 px (2 columns), flex-grow will overwrite the max-width and allow the element to occupy the remaining available space.

.container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.container > div {
  width: 480px;
  flex-grow: 1;
}

input {
  display: block;
  width: 100%;
  box-sizing: border-box;
}
<div >
  <div>
    <input>
    <label>Firstname</label>
  </div>
  <div>
    <input>
    <label>Lasttname</label>
  </div>
</div>

CSS-Grid auto-fit:

This Grid solution uses minmax and auto-fit to create columns dynamically. It will fit as many columns as possible but ensures that no column is less then 480px (unless the screen is smaller) and resize the columns to occupy remaining space.

.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(480px, 1fr));
  gap: 20px;
}

input {
  display: block;
  box-sizing: border-box;
  width: 100%;
}
<div >
  <div>
    <input>
    <label>Firstname</label>
  </div>
  <div>
    <input>
    <label>Lasttname</label>
  </div>
</div>

CodePudding user response:

by set width: 100%; and max-width to any value like max-width: 400px; you can do this

.my-div {
  width: 100%;
  max-width: 400px;
  
  /* center */
  margin-inline: auto;
  
  /* just for demo */
  background: #808080;
  height: 50em;
}
<div ></div>

  • Related