Having difficulty creating a basic container

As a beginner in web development using html/css, I am eager to learn and create something simple.

I want to design a responsive fixed box that always maintains a 20px distance from the viewport edges.

The idea is that as the screen size changes, the box will consistently have a 20px margin on all sides without any scrolling necessary. Additionally, I envision placing a .gif at the center of this box that scales with the screen size, approximately 40em in size.

However, I've encountered challenges in achieving this design. Despite trying various solutions and consulting multiple tutorials, I have yet to find one that completely eliminates issues such as unwanted scrollbars, uneven margins, or difficulty controlling the layout.

If you have any advice or guidance on how to accomplish this design accurately, I would greatly appreciate it!

Below is an example of my current attempt, though it represents just one of many failed trials. (the .gif image is not included)

body {
  background: #f0e8e6;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
}

div {
  width: 90vw;
  height: 90vh;
  padding-top: 100px;
  padding-bottom: 100px;
  padding-left: 100px;
  padding-right: 100px;
  position: center;
  top: 50%;
  left: 50%;
  background: #ffffff;
  text-align: center;
  overflow: hidden;
}
<div>

</div>

https://i.sstatic.net/RsoYv.jpg

Answer №1

This method may seem a bit unconventional, but I find it to be quite effective due to its straightforward logic. The key is to apply the margin to the parent element using padding, rather than the child element.

body {
  background: #f0e8e6;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
  padding: 0;
  margin: 0;
  width: 100vw;
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
}

div {
  width: 100%;
  height: 100%;
  background: #ffffff;
  text-align: center;
  overflow: hidden;
}

To start, remove the default padding/margin of the body. Next, add padding to the body to create the 20px margin effect. Ensure that the body spans the full width of the page, and the div spans the width of the body by adjusting their respective width/height properties.

An important property to note here is box-sizing, which prevents the container from expanding when adding padding. Without this, the body would overflow the page.


To center an image, utilizing flex is recommended. While it's a complex topic, it suits these scenarios perfectly. For more information on flex, visit here. Below is an example demonstrating how to align the image vertically and horizontally using align-items and justify-content.

body {
  background: #f0e8e6;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
  padding: 0;
  margin: 0;
  width: 100vw;
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
}

div {
  width: 100%;
  height: 100%;
  background: #ffffff;
  text-align: center;
  overflow: hidden;
  
  display: flex;
  align-items: center;
  justify-content: center;
}
<!doctype html>

<html>
<head>
  <meta charset="utf-8">
  <title>loiz</title>
  <link rel="stylesheet" type="text/css" href="styling.css" media=”screen” />
</head>

<body>
  <div>
    <img src="https://via.placeholder.com/150C/O"/>
  </div>
</body>

</html>


Keep in mind that the top and left css attributes are applicable only to elements with absolute or fixed positioning (refer to here).

Additionally, position: center is not a valid value. Please check valid values for positioning here.

Answer №2

Here is one suggested approach:

/* Using CSS custom properties to set a consistent margin value: */
:root {
  --margin: 20px;
}

/* Applying the same box-sizing method, font style, margin, and padding to all elements: */
*,
 ::before,
 ::after {
  box-sizing: border-box;
  font: normal 1rem / 1.5 sans-serif;
  margin: 0;
  padding: 0;
}

body {
  /* Removed irrelevant properties for this demo; added background color for visualization: */
  background-color: white;
}

div {
  /* Using flex display for easier content positioning vertically/horizontally: */
  display: flex;
  /* Calculating width and height using viewport units minus margins: */
  width: calc(100vw - 2 * var(--margin));
  height: calc(100vh - 2 * var(--margin));
  /* Applying margin around the <div>: */
  margin: var(--margin);
  /* Background color for layout visualization: */
  background-color: red;
}

div img {
  /* Centering the <img> both horizontally and vertically: */
  margin: auto;
  /* Set width to maintain aspect ratio with height adjusted accordingly by the browser: */
  width: 40vw;
}
<div>
  <img src="https://via.placeholder.com/300.gif/09f/fff" alt="Placeholder gif">
</div>

Check out these references for more information:

Answer №3

To ensure responsiveness on various devices, implementing media queries is essential. Set a 2% padding to the outermost div, insert your gif into this div with additional padding for optimal display results.

Answer №4

If you're looking to achieve this, here's a suggestion:

body {
  background: red;
  padding: 0;
  margin: 0;
  display: flex;
  height: 100vh;
}

div {
  width: calc(100vw - 40px);
  height: calc(100vh - 40px);
  background: #ffffff;
  overflow: hidden;
  margin: auto;
  display: flex;
}

img {
  width: 40vw;
  margin: auto;
}
<div>
  
  <img src="https://images.pexels.com/photos/10262654/pexels-photo-10262654.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/>
   
</div>

Answer №5

If you're dealing with default padding and margin on the body tag, it's important to reset them first. Additionally, the html tag is not full height by default, so you'll need to make it fullscreen by adding width: 100% and height: 100%.

To resize your div correctly, consider using the calc method in CSS. For example, you can set the width as width: calc(100% - 240px), where 240px represents 200px of padding (100px each) on both sides and a 40px margin (20px each).

When centering a gif, it's recommended to utilize flex features rather than relying solely on text-align adjustments.

:root {
    --margin:  20px;
    --padding:  100px;
}
body, html {
    width:  100%;
    height: 100%;
    margin:  0;
    padding:  0;
}
body {
  background: #f0e8e6;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
}

div {
  width: calc(100% - (var(--margin) * 2) - (var(--padding) * 2));
  height: calc(100% - (var(--margin) * 2) - (var(--padding) * 2));
  padding:  var(--padding);
  background: #ffffff;
  overflow: hidden;
  position: relative;
  display:  flex;
  align-items: center; 
  justify-content: center;
  left: var(--margin);
  top:  var(--margin);
}
<div>
    <img src="https://media0.giphy.com/media/WXZ5DqIOhQrxtkcszN/giphy.gif?cid=ecf05e47yzd9cgsu3pzebujrmdl3od4erxhdtwozizzjx2nc&amp;rid=giphy.gif&amp;ct=g" alt="Hell Yeah Snl GIF by Saturday Night Live" style="width: 500px; height: 280px; ">
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to close Bootstrap sidebar menu on mobile devices

I implemented a sidebar menu for mobile that opens when you click on the hamburger icon, with a dark overlay covering the body. The issue I encountered is that on mobile devices, the visibility of the menu does not change when clicked outside of it. It wor ...

Splitting a td tag into multiple columns dynamically with Angular

I am attempting to dynamically split the table element into separate columns. My desired layout should resemble this: https://i.sstatic.net/C81tg.png The values for name and surname are fixed at 1, but the values for subjects and grades can vary (there ma ...

It appears that WebClient.DownloadString has a tendency to alter certain aspects of the HTML code retrieved from an external website

I have a website built with ASP.NET (.aspx) that I access from an ASP.NET MVC 4 mobile site (.cshtml) to retrieve its HTML response string. Both sites are hosted on a Windows Server 2008 R2 system and were developed using VS2010 Professional. -When direct ...

Both Fluid and Fixed layouts offer different advantages and disadvantages for website

Is there a way to position two divs side by side, where one div is 75% width and the other is 25% width? Additionally, can we place another div on top with margin:0 auto; to center the content of the page with a width of 986px? Here is an example code sni ...

Is it feasible to have fixed headers adopt the width property?

Is there a way to align the widths of table elements while maintaining a fixed header row? If the 'fixed' property is disabled, the width spaces correctly but the header won't stay fixed and will scroll out of the container div. Enabling the ...

What causes background-color to create gaps of white space?

How can I remove the white spaces on the right and left side of a section when applying a background-color? https://i.sstatic.net/WbVuv.png I want the background-color to fill out the entire width of the section. Should I use extra padding to solve this ...

When utilizing dynamic binding within *ngfor in Angular 4, the image fails to display properly

I'm encountering an issue with an <img> tag that isn't behaving as expected in my code snippet: <div *ngFor="let familyPerson of userDataModel.family" class="col-md-6 col-lg-4 family-member"> <div class="fm-wrapper"> ...

Ensure that the Materialize CSS modal form remains open even after submission

Is there a way to reload a form inside a materialize modal with empty fields without closing the modal after submitting? The issue is that currently, when the submit button is clicked, the modal closes and redirects. <div class="modal" id="docM ...

Is your idTabs design in need of some sprucing up

Just stumbled upon idTabs and trying to implement a basic one on my server. I've taken the code from the 'Usual' page, included the plugin file and jQuery, but all I'm seeing is... - Tab 1 - Tab 2 - Tab 3 This is tab 1. Seems like it& ...

How can text be extracted from BeautifulSoup without displaying the opening tag and before the <br> tag?

I have recently started learning Python and Beautiful Soup, and I've spent a significant amount of time trying to solve this particular issue. I am looking to extract three specific text elements from a <div> that does not have a class attribu ...

What is the best way to ensure that all rows in flexbox have the same number and dimensions as the first row?

My objective with flexbox was to evenly distribute the text across the width of the page. When I say 'evenly distributed', I mean: If there are 3 sections, the center of the text in each section should be at fifths of the webpage width. This is ...

Tips for modifying the color of the last anchor in a list item

li elements are utilized to create breadcrumb in a shopping cart. The breadcrumb displays all anchor elements using the style defined for an 'a' element from site.css. How can I make the last anchor's color black? I attempted the style belo ...

Having trouble displaying the fancybox helper buttons

I had everything working perfectly, but suddenly it stopped and I can't figure out what went wrong. I just need the left, right arrows, and helper buttons to appear when fancybox is open. Any assistance would be greatly appreciated. PS: All the neces ...

Creating animated effects through Javascript and CSS triggered by user events

As a beginner in javascript and CSS, I am experimenting with creating a simple animation that adjusts the transparency of an image when triggered by an event. However, I am facing an issue where the animation only works every other time the function is cal ...

"Utilizing Box elements, implementing linear gradients, styling with CSS, and

Currently, I am working on a project that involves using react JS and I am trying to find a solution for implementing linear gradient in multiple boxes. Specifically, I want to achieve the effect of having three identical boxes lined up next to each other. ...

Incorporating smooth sliding animation to ng-repeat elements

Our team has developed a custom widget in ServiceNow that displays a row of icons and reveals or hides additional details in a div when icons are clicked. Below is the structure of our html and client controller: <div class="icons"> <ul class=" ...

Extracting text from HTML tags can be quite tricky, especially when you need the text within a specific tag like <td> but not within any nested tags like <

Is there a way to extract only the numbers from the <td> tag and ignore any text within the <strong> tag that is nested inside it? I am currently using selenium code but it returns the entire content of the <td> tag. Python Code: wait. ...

Completely shrink the middle row first when resizing the browser before shrinking the other rows

Utilizing a simple three row structure: <div class="EditorHeaderWrapper"> <h1>Title</h1> </div> <div class="EditorMainRowWrapper"> // Content of the main row goes here </div> <div class="EditorFooterWrapper"> ...

Aligning characters according to Unicode standards

I'm looking to showcase a Unicode character at the center of a button. Below is the code snippet: <div class="col-xs-1"> <button class="btn btn-tool"> <span></span> </button> </div> span:before { ...

Is there a way to adjust the height pixel value in my code so it can be dynamic?

I have created a simple script that allows selected objects to fade in as the user scrolls down. However, my issue is that this script is quite rigid. If I were to apply it to 20 different objects, for example, I would need to manually adjust the height ea ...