简体   繁体   中英

How do I make the margins of a webpage shrink on horizontal window resize?

In the Adirondack template from Squarespace, there's a super crazy responsive feature where if you resize the window horizontally, the "margins" of the page start shrinking until it just kinda locks onto the main content of the page. I included a GIF of what I'm trying to articulate below.

How could I go about replicating that effect? All my attempts have just resulted in the entire page shrinking to scale instead of just the margins. (In my attempt, I styled the main content of the div to have margins from the left and right to replicate the kind of look in this template.)

保证金缩小效果的GIF动画

You can achieve this without using margins or media queries. Just use max-width on the content, ie

.content {
  // Make it as wide as possible…
  width: 100%;
  // … but only up to 250px
  max-width: 250px;

  // Center horizontally within parent
  margin: 0 auto;
}

Example:

 function updateWidth() { const slider = document.querySelector(".slider"); document.querySelector(".parent").style.width = `${slider.value}%`; } 
 input { width: 100%; } .parent { background-color: #cecece; padding: 5px 0; } .child { background-color: red; width: 100%; max-width: 250px; margin: 0 auto; padding: 5px 0; text-align: center; color: white; } 
 Use the slider to simulate resizing: <input type="range" value="100" min="0" max="100" oninput="updateWidth()" class="slider" /> <div class="parent"> <div class="child">Content</div> </div> 

I normally center the main content div using margin-left: 50% and transform: translateX(-50%) . Just make sure to use the various cross-browser rules when using transform. After that just set the divs width and max-width. See below or this fiddle.

 body { width: 100%; float: left; display: block; padding: 0; margin: 0; } .main-centered-div { color: #000000; width: 100%; max-width: 1180px; margin-left: 50%; transform: translateX(-50%); -webkit-transform: translateX(-50%); -moz-transform: translateX(-50%); -ms-transform: translateX(-50%); -o-transform: translateX(-50%); background: #eeeeee; } 
 <!DOCTYPE html> <html> <head> </head> <body> <div class="main-centered-div"> Some content for my div. Some content for my div. Some content for my div. Some content for my div. Some content for my div. Some content for my div. Some content for my div. Some content for my div. Some content for my div. Some content for my div. Some content for my div. Some content for my div. Some content for my div. Some content for my div. Some content for my div. Some content for my div. </div> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM