Instructions on how to perfectly center a square SVG both horizontally and vertically using CSS, ensuring that only the image is displayed within the viewport regardless of its size

Trying to display an SVG on mobile and desktop browsers has its challenges. The square shape of the SVG makes centering it vertically and horizontally using 'contain' ineffective, resulting in a centered square image, which is not the desired outcome.

The goal is to center the image and zoom in on it, displaying only part of the image with the rest clipped by the viewport. Unfortunately, images cannot be uploaded for demonstration purposes, but the following drawing should provide clarity:

Mobile:

  ┌┄┄┄┄╔═══════╗┄┄┄┄┐
  ┆    ║       ║    ┆
  ┆    ║       ║    ┆
  ┆    ║       ║    ┆
  ┆    ║       ║    ┆
  ┆    ║       ║    ┆
  ┆    ║       ║    ┆
  └┄┄┄┄╚═══════╝┄┄┄┄┘
        ^           ^
        |           |
  viewport          image

Desktop:

                image
                |
                v
       ┌┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┐
       ╔═════════════════╗    
       ║                 ║    
       ║                 ║    
       ║                 ║    
       ║                 ║<-- viewport  
       ║                 ║    
       ║                 ║    
       ╚═════════════════╝
       └┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘

Attempts at using 'object-fit: cover' have proven unsuccessful so far.

Answer №1

yourSelector {
  background: url('path/to/your/svg') center /cover;
}

The code snippet above will achieve the desired effect.
In the shortcut provided, /cover represents

background-size: cover;

Verify the outcome below:

div {
  background: url('https://example.com/image.svg') center /cover;
}
.one{
  height: 200px;
  width: 50%;
}
.two {
  height: 100px;
  width: 100%;
}
.three {
  height: 400px;
  width: 100px;
}
.four {
  height: 200px;
  width: 200px;
}
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>

You can also use it as a background-image for the <body>:

body {
  background: url('https://example.com/image.svg') center /cover;
  margin: 0;
  min-height: 100vh;
}

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 is the reason behind the addition of right padding to texts containing non-ASCII characters?

Upon observation of the image below, it is evident that text containing non-ASCII characters tends to be pushed away from the right margin, while text with emojis is pushed closer to the margin. Have you ever wondered why this happens? https://i.stack.img ...

Bootstrap modal with sticky-top class displays abnormal margin and padding upon being shown

Whenever I launch a bootstrap modal, I notice unexpected side padding or margin appearing on certain HTML elements. For instance: Before displaying the modal: <div id="fixedMenu" class="d-none container-fluid menu sticky-top px-0" s ...

Creating geometric designs on an image and storing them using PHP

I am attempting to retrieve an image from a specific location on my server, draw lines on it, and then save the modified image back to the same location. Below is the code I am using: function drawShapes($src_path, $json) { echo "---inside dra ...

Ionic - encountering crashes with ion-nav-view on emulator

I am encountering an issue with ion-nav-view. Whenever I try to use it, the emulator displays a black screen, but it works perfectly fine in ionic serve. I suspect it may be a syntax error causing this problem. Interestingly, when I create a blank projec ...

A guide on encrypting the data of a file that is uploaded in Meteor.js

As a newcomer to Meteor and coding in general, I have completed tutorial projects and examples and now feel ready to start my own project. I want users to be able to select a file from their computer using an input field, read the contents of the file, and ...

jQuery not loading SCRIPT src after appending to HTML

I'm in the process of developing an application that requires me to load new HTML content and append it into the current page's HTML. So far, I've been able to load the new HTML using jQuery ajax. However, within this newly loaded HTML, the ...

Monitor File Tool for JetBrains IDE - CSS Optimization Setup - Streamline CSS Automatically

Utilizing the File Watcher tool in Jetbrains IDE (Webstorm and Rider) to automatically minify .css files and generate corresponding .min.css files for the entire project has been my goal. However, a challenge arises when it starts minifying files that alr ...

Is it possible to arrange buttons next to each other?

Here is the code for a specific page: HTML: <div class=main> <div class=bttn> <button>abcdef</div> <div class=content> <a href=#!>jksg</a> <a href=#!>jksg</a> & ...

Preventing data loss upon submitting a form (PHP)

Currently, I have an HTML file that allows users to select appointment times for specific days of the week. Once they click submit, a PHP file generates and displays a calendar with the chosen times as checkboxes. My goal is to enable users to input their ...

Having trouble with jQuery div height expansion not functioning properly?

Having a bit of trouble with my jQuery. Trying to make a div element expand in height but can't seem to get it right. Here's the script I'm using: <script> $('.button').click(function(){ $('#footer_container').anim ...

retrieving the webpage's HTML content from the specified URL using AngularJS

Utilizing the $http.get('url') method to fetch the content located at the specified 'url'. Below is the HTML code present in the 'url': <html> <head></head> <body> <pre style = "word-wrap: break ...

Hover effect not functioning as expected on Mobile Safari

Looking to create a hover effect for images on an HTML website. The idea is to have the image shade and display details when hovered over. Here is the CSS code: /* Hover overs */ .folio4:hover .face { opacity:1; cursor: pointer; } ...

Fixing Email Validation Error in AngularLearn how to troubleshoot and resolve

I'm encountering an issue when trying to develop an email center using regex pattern, as I'm receiving a validator error in HTML. I have already installed ngx-chips and angular-editor, imported all the necessary modules and dependencies. Here is ...

Unexpected behavior observed with Mui theme breakpoints

I have defined breakpoints for my MUI React-based app like so export const lighttheme = createTheme({ palette: palette, typography: typography, breakpoints: { values: { xs: 0, sm: 600, md: 900, lg: 1200, xl: 1536, ...

The function req.send('null') does not exist in the Node.js MySQL library

I am struggling with inserting a form into a MySql database. The values are stored in the database from the form, but the table displayed on the page does not refresh. I can only see the entries when I restart the server and revisit the page. Furthermore, ...

Having trouble with the expand feature of Bootstrap 5 navbar

I am facing an issue with my Bootstrap 5 navbar as it only extends as wide as the contents within it. I want the navbar to expand the entire length of the container but changing the navbar-expand-?? setting doesn't seem to have any effect. https://i.s ...

What could be causing appendChild to malfunction?

I'm having an issue trying to create three elements (parent and one child) where the third element, an <a> tag, is not appending to modalChild even though it's being created correctly. modal = document.createElem ...

What is the best way to insert a JavaScript variable into a filter while using ng-repeat?

I'm currently working on a situation where I have the following code: <div ng-repeat="i in MediaFeedItems | filter: { category: 'userSelect' }" class="mediafeed--item"> This specific code snippet is responsible for iterating through ...

Switch up your code and toggle a class on or off for all elements that share a specific class

I've been attempting to create a functionality where, upon clicking a switch, a specific class gets added to every element that is assigned the class "ChangeColors". Unfortunately, I have encountered some difficulties in achieving this task. The error ...

Plotly Express Unleashes the Power of Subplots

After spending countless hours scouring the internet, I am feeling utterly frustrated and perplexed about how to deal with subplots using plotly express in Python. The concept is to create a line plot alongside a scatter plot and another line plot, where ...