Using a percentage in CSS translate can result in an image appearing blurry

I am facing a frustrating issue.

Whenever I align an image using percentage-based transform translate, it results in a slight blur. This problem is specifically related to percentage alignment.

Here is the CSS snippet:

img {
  display: block;
  height: auto;
  max-width: 100%;
  transform: translate(1%,1%); 
}

I have tried various solutions:

  1. translate3d fix
  2. perspective fix
  3. translateZ fix

If anyone has a solution, please let me know!

Updated: Js Fiddle I have updated the js fiddle with an image to better demonstrate the difference. The blurriness is especially noticeable in photography.

Example of the issue:

https://i.stack.imgur.com/eRjov.png

Thank you!

Answer №1

You can experiment with using the following code snippet: translateX(calc(-50% + 0.5px))

Answer №2

When using a percentage value with Transform: translate, it can lead to sub-pixel accuracy in positioning elements. This can cause blurriness in your images due to less than optimal anti-aliasing by the browser. To maintain sharpness, consider positioning elements with whole-pixel values instead.

A possible workaround involves measuring and adjusting offset values using JavaScript. By calculating the difference between pre and post-translate offsets and rounding them to the nearest whole pixel, you can reapply these values as pixels instead of percentages. While not an ideal solution, it can help keep your images crisp.

Although this method sacrifices responsiveness and may overwrite other Transform attributes, such as translateX or translateY, it provides a practical way to improve image clarity.

If needed, here is a function that accomplishes the aforementioned process:

function snapTranslateXYValsToNearestPixel(element){
  var xTransPos = $(element).offset().left;
  var yTransPos = $(element).offset().top;
  // turn off any transitions (but save values first):
  var transitionVal = $(element).css('transition');
  $(element).css('transition', 'none');
  // turn off translate:
  $(element).css('transform', 'translateX(0) translateY(0)');
  var xPosDiff = xTransPos - $(element).offset().left;
  var yPosDiff = yTransPos - $(element).offset().top;
  var xPixelVal = Math.round(xPosDiff);
  var yPixelVal = Math.round(yPosDiff);
  var translateVal = 'translateX(' + xPixelVal + 'px) translateY(' + yPixelVal + 'px)';
  $(element).css('transform', translateVal);
  // reapply transition value (wait one tick for new css value to apply first):
  setTimeout(function() {
    $(element).css('transition', transitionVal);
  }, 1);
}

To use this function, simply call:

snapTranslateXYValsToNearestPixel('.align-per');

Answer №3

I recently encountered a similar issue with an overlay that is positioned in the center of the window using CSS, with its size determined by the content and limited by maximum height and width. Despite trying various CSS solutions, none seemed to work.

To address the problem, I implemented a JavaScript function to ensure that the overlay's dimensions are always even, which resulted in sharper visuals without the need for timeouts to preserve transitions.

Below is the JavaScript function I used:

fullPixelFix = function() {
  var overlay = $('#overlay');
  overlay.removeAttr('style');
  var dividable_width = Math.round(overlay.outerWidth() / 2) * 2;
  var dividable_height = Math.round(overlay.outerHeight() / 2) * 2;
  overlay.outerWidth(dividable_width).outerHeight(dividable_height);
  overlay.css(maxWidth: dividable_width, maxHeight: dividable_height);
}

Answer №4

I came across this solution on a forum discussing the issue of blurry text with CSS transformations: CSS: transform: translate(-50%, -50%) makes texts blurry

div.align-per {
  transform: translate(1%, 1%) translateZ(0) ;
  -webkit-transform: translateZ(0) scale(1.0, 1.0);
}

It might be worth exploring for compatibility with other browsers.

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

What could be causing my page to suddenly disappear?

After saving my changes in the IDE and refreshing the browser to test the prompt() function in my index.js file, the entire page goes blank, showing only a white screen. I double-checked the syntax of my function and it seems correct. Everything else on th ...

Generating a business card example using node-html-pdf on an Ubuntu operating system

I am currently attempting to utilize the node-html-pdf module on Ubuntu 16.04 by following the businesscard example provided at https://github.com/marcbachmann/node-html-pdf. Regrettably, I encountered difficulties in generating the PDF file. To begin wi ...

Preventing Jquery Append from Adding Previous Elements

I am struggling to figure out how to display the star rating for each hotel individually. I have 5 hotels, each with a different star rating. Here is my Javascript code: function GetStarHotel() { var parent = $(' p.star '), imagePat ...

Tips for extracting HTML entities from a string without altering the HTML tags

I need assistance with removing HTML tags from a string while preserving html entities like &nbps; & é < etc.. Currently, I am using the following method: stringWithTag = "<i> I want to keep my ->&nbsp;<- element space, bu ...

What is the best way to identify the position of an element in an array given my specific circumstances

I am trying to utilize the ng-repeat directive in order to display an array. Here is what I have: <div ng-repeat="stu in school"> <div>{{stu.name}}</div> <div>{{stu.grade}}</div> </div> JavaScript $scope.scho ...

Tips for effectively utilizing innerHTML in this particular scenario

For an assignment, we were tasked with creating a Madlib game where users input words into textfields to replace certain words in a hidden paragraph within the HTML using JavaScript and CSS. The paragraph embedded in the HTML page is as follows: <span ...

stopPropagation() halts the propagation in the opposite direction

I encountered an issue while attempting to create a non-clickable div. While it does stop propagation, it doesn't prevent what should be stopped and allows things that shouldn't be clickable. js //screen has set stopPropagation $("#smokeScree ...

What is the best way to update the div id by extracting the last digits from a number?

Is there a way to change the div ids using a function? Before: <div id="a_1">a1</div> <div id="b_1">b1</div> <div id="c_1">c1</div> <div id="d_1">d1</div> <button onclick="change()">Change</button& ...

How can I add information into a nested div element?

I encountered an issue when attempting to insert data into my block. The div structure is as follows: <div class="1"> <div class="2"> <div class="3"> <div class="4"></div> </div> ...

Why isn't the input appearing on the succeeding line below?

<label for="email2">Enter Your Email Address</label> <input type="text" name="email2" id="email2" placeholder="example: [email protected]"> <label for="phone2">Phone Number</label> <input type="text" name="phone2" id= ...

Conceal element when unchecked

There is a checkbox pre-selected labeled "Use profile address" with the address displayed below. If the customer unchecks the checkbox, the address that was shown before will disappear and a new input field for adding a different address will appear. I a ...

PersistJS callback function is malfunctioning

I stumbled upon a great library for managing client storage. You can find the latest version here: https://github.com/jeremydurham/persist-js However, I encountered an issue with the callback function. var result = store.get('saved_data', func ...

Using CSS files in the web directory in CakePHP and connecting them to HTML

Could someone offer some help with cakephp? I'm experiencing an issue related to routes that I can't seem to resolve. I've organized all my css files in webroot/css within my app. In my default layout, I included a html link <link href=" ...

Creating a CSS template for organizing sidebar and footer divisions on a webpage

I am facing an issue with the layout of my website. I have a container that is positioned relatively and houses various divs for header, sidebar, main-content, and footer. The problem lies with the sidebar and footer components. The sidebar has been posit ...

The previous method of using `vue/compiler-sfc ::v-deep` as a combinator has been phased out. Instead, opt for the new syntax `:deep(<

When developing with Nuxt 2, I am encountering numerous [@vue/compiler-sfc] ::v-deep usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead. errors when running npm run dev. After attempting to resolve the issue by changing a ...

Expanding image size with CSS

Looking for assistance to fix the squished image in HTML & CSS. I used the CSS code provided by Figma to style the image in html, but it resulted in a different aspect ratio from the original picture, causing the image to appear squished. Any help is appr ...

Setting a CSS grid column to have a minimum width of `max-content` and a specific

I am trying to create a CSS grid where the column widths adjust based on the content, but with a minimum width of 100px. I attempted using minmax(max-content, 100px), however it did not produce the desired result. In the example below, the narrow column sh ...

Encountering a problem when attempting to send an HTML email through PHP

Trying to use PHP to send email within an HTML code snippet. Here's the code I've written: <?php if($_SERVER['REQUEST_METHOD'] == 'POST') { if ( mail ('<a href="/cdn-cgi/l/email-protection" class="_ ...

Discovering visible ID numbers on the screen

My content includes the following: <div id="sContainer"> <div class="message0" id="l0">Initial Content 111</div> <div class="message1" id="l1">Initial Content 222</div> <div class="message2" id="l2">Initial ...

Unable to retrieve the values from document.getElementById("") or document.getElementById("").innerHtml appears to be malfunctioning

I am currently working on an HTA application that includes multiple <input type="text"> fields for users to input data. My goal is to pass this data to a VBScript for processing. Below is the HTML structure: <div id="tableContent" name="tableCon ...