How to center a div that is absolutely positioned using translateX and has overflow auto while avoiding the use

Here is a simple way to center and maintain the full size of a div, but there seems to be an issue. Take a look at this code snippet:

* {
      box-sizing: border-box;
    }

    .body {
      width: 400px;
      height: 100px;

      float: left;

      margin-right: 20px;

      position: relative;
    }

    .body.smaller {
      width: 200px;
    }

    .container {
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;

      position: absolute;

      overflow: auto;

      border: 2px solid blue;
    }

    .child {
      width: 300px;
      height: ...
    
<div class="body">
      <div class="container">
        <div class="child"></div>
      </div>
    </div>

    <div class="body smaller">
      <div class="container">
        <div class="child"></div>
      </div>
    </div>

This code snippet shows that the first sample is properly centered and rendered, but the smaller one has some cropping issues on the green border on the left.

I'm looking for a way to display the entire content of the div using the 'translateX' transform option without relying on tricks like 'margin: 0 auto;' or similar methods.

I have experimented with various combinations of scaled container divs and scrollable child divs, but I haven't had any success so far.

Update: Please note that these sizes are just examples and not definitive. No forced calculations should be necessary to achieve the desired outcome.

Update 2: The 'margin: 0 auto;' method cannot be used to center the div as I am aiming for a specific result. Check out this JSFiddle: https://jsfiddle.net/Emulator000/79c5L6o8/12/

function scale() {
        let children = document.getElementsByClassName('child');
        for (let i = 0; i < children.length; i++) {
          children[i].style.transform = 'scale(3)';  
        }
    }
* {
      box-sizing: border-box;
    }

    .body {
      width: 400px;
      height: 100px;

      float: left;

      margin-right: 20px;

      position: relative;
    }

    .body.smaller {
      width: 200px;
    }

    .cont...
    
    
<button onclick="scale()">Scale</button>

If you click the "Scale" button, you can see that the smaller div scales correctly and allows scrolling as expected. However, the larger one leaves empty space as it starts scaling with a fixed margin. This issue also occurs with other techniques like justify, box alignment, or centered text using 'display: inline-block'.

Answer №1

Give this a try:

* {
  box-sizing: border-box;
}

.body {
  width: 400px;
  height: 100px;
  
  float: left;
  
  margin-right: 20px;

  position: relative;
}

.body.smaller {
  width: 200px;
}

.container {
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  
  position: absolute;
  
  overflow: auto;
  
  border: 2px solid blue;
}

.child {
//width: 300px;

  width: 80%;
  height: 1000px;
  
  position: absolute;
  
//left: 50%;  
  left: 10%;
  
//transform: translateX(-50%);   
  border: 2px solid green;
}
<div class="body">
  <div class="container">
    <div class="child"></div>
  </div>
</div>

<div class="body smaller">
  <div class="container">
    <div class="child"></div>
  </div>
</div>

Answer №2

After resizing, the scroll bar fails to display the correct margin, requiring removal of the excess.

<head>
</head>
<style>
 * {
  box-sizing: border-box;
}

.body {
  width: 400px;
  height: 100px;
  
  float: left;
  
  margin-right: 20px;

  position: relative;
}

.body.smaller {
  width: 200px;
}

.container {
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  
  position: absolute;
  
  overflow: auto;

  
  border: 2px solid blue;
}

.child {
  display: block;
  
  width: 300px;
  height: 1000px;
  
  margin: 0 auto;
  
  border: 2px solid green;

  transform-origin: 0 0;
}
</style>

<body>
<div class="body">
  <div class="container">
    <div class="child">Lorem, ipsum dolor sit amet consectetur, adipisicing elit. Optio sequi quos amet, doloremque earum assumenda sapiente recusandae explicabo fuga, sed provident! Aspernatur ex neque maiores voluptatibus reprehenderit! At, quasi laboriosam.</div>
  </div>
</div>

<div class="body smaller">
  <div class="container">
    <div class="child">Lorem ipsum dolor sit amet consectetur adipisicing elit. Eius iusto numquam, autem eligendi voluptas ab qui id soluta voluptatum molestias sapiente dignissimos enim illo, impedit omnis tempore, corporis, ipsam accusantium.</div>
  </div>
</div>

<button onclick="scale()">Scale</button>
<script type="text/javascript">
    
    function scale() {
      let children = document.getElementsByClassName('child');
    for (let i = 0; i < children.length; i++) {
      children[i].style.transform = 'scale(3)';
      // Remove the margin 
      children[i].style.margin = '0';  
    }
  }
</script>
</body>

</html>

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

Passing HTML form variables to the controller in C# .NET Core

I'm struggling with passing a variable from an HTML form to a controller in my .NET Core project. The variable I pass to the controller is then used in a method call within an interface. Here's my data model for the form: public class JourneyFor ...

Resize images smoothly without disrupting the anchor scrolling

I have created a website with the following design: (Caution: The site is built using AngularJS on a server that may not serve it correctly - please visit directly instead of using browser reload.) However, I am facing two conflicting requirements... ...

What is the best way to stop the content in :after from wrapping onto the following line?

How can I add a divider "/" after each li element in my Bootstrap-based menu without it wrapping to the next line? The code I am using can be found here: http://jsfiddle.net/zBxAB/1/ I have tried using inline-block to prevent the slash from wrapping, but ...

Is it advisable to avoid using `&apos;` for escaping single quotes?

According to the insights shared in conversations about the popularity of single quotes in HTML and Jquery embedded quote in attribute, the Wikipedia page on HTML highlights that: The use of the single-quote character ('), as a way to quote an attri ...

Is there a way to adjust the size of this map?

I’m attempting to adjust the dimensions of the div.wx-imap-pane.wx-module to a height of 346px and a width of 1727px using greasemonkey, but I’m struggling to make the change take effect. My attempt: div#div.wx-imap-pane.wx-module, div#div.wx-imap-pa ...

What is stopping me from utilizing ES6 template literals with the .css() method in my code?

I am currently working on a project where I need to dynamically create grid blocks and change the color of each block. I have been using jQuery and ES6 for this task, but I am facing an issue with dynamically changing the colors. Below is the snippet of m ...

I'm curious if it's possible to effectively navigate within frames on a webpage using Nightmare JS

I'm encountering issues with using Nightmare js to access elements within a specific frame on a webpage that pulls its elements from a separate HTML file. These frames are not iframes, so typical plugins like iframe-manager are not effective in this s ...

Is it possible to protect passwords internally via URL and AJAX?

During my time at a previous company, we had an internal website that required a password to be entered at the end of the URL in order to view it. I suspect this was done using AJAX, but I am unsure. Even if AJAX was used, I do not know how to code it myse ...

Toggling the legend and row on click functionality in Google charts

I have a specific requirement that involves a Google chart: Once a Google chart is loaded, I need the ability to click on a legend, which will then gray out the legend and remove its corresponding value from the graph. If I click on the grayed-out le ...

Is there a different method like Calc() to create a static sidebar alongside content?

Is there a way to achieve a fixed sidebar on the left and a content area on the right without using calc() in CSS? I'm looking for a more universally supported method that works across different browsers. .left-sidebar { width: 160px; ...

Ensure that Roboto font is utilized on IE 11 and Edge browsers

My goal is to implement the Google Roboto font in my project, but I'm noticing that it doesn't display properly in IE11 / Edge browsers. Below is a snippet of my code: <!DOCTYPE html> <html> <head lang="en"> <meta charse ...

Unable to automatically play a YouTube video that is covered by a custom thumbnail

Currently, I have set up a custom thumbnail for a YouTube video on my website. However, when the user clicks on the thumbnail, they are directed to the video page and must click again to start playing the video. I would like the video to automatically play ...

Implementing a click event on an image in an Angular 4 application

I'm facing an issue with adding a click event to an image within an Angular component. I have tried the following code: <img src="../../assets/add.svg" width="18" height="18" (click)="addItem()"> However, this approach does not seem to work as ...

instructions for ensuring gridview spans entire width of panel

I have a gridview that is contained within a panel. I am trying to make the gridview fill 100% of the width and height of the panel. This is what I've attempted so far: CSS .pnlGridView { position:relative; float:right; heig ...

Fetching data in VueJs before redirecting to a new page

Within the mounted function, I am creating an action that fetches data from a Rest API and populates my table in a Vue.js component mounted() { UserService.getProjects().then( (response) => { this.isProject = true; this.project ...

Do class bindings with variables need to be inline when using Vue 3?

Consider the following HTML: <template v-for="(child, index) in group"> <div :class="{'border-pink-700 bg-gray-100 ': selected === child.id}"> <div>Container Content</div> </div> & ...

Detect keyup event within a dynamically injected iframe

I am currently using a text editor that utilizes wysihtml5. I suspect the text editor is embedded within an iframe. My goal is to capture the key up event inside the text editor and prevent scrolling within it. Below is the code snippet that loads the tex ...

Implementing Ng-debounce selectively for functions within an AngularJS application

I am looking to execute specific functions at different time intervals when there is a change in input. The current setup is as follows: <input type="text" name="title" ng-model="title" placeholder="Search..." ng-model-options="{ updateOn: 'defaul ...

JQuery: Techniques for accessing the assigned font of an element

Can the assigned font of an element be retrieved using jQuery? For example, if there is this CSS: #element { font-family: blahblah,Arial; } In the above case, the Arial font will be assigned to #element. Is it possible to extract that information using ...

What's the best way to enhance the appearance of the hyperlink in this code snippet?

<p class="butonat"> <a href="#"><span class="color1">Explore More&nbsp;</span></a> I attempted the given styling but it did not produce the desired result: Styling (provided in comment post by original poster): .butonat ...