Ensure that the responsive SVG image remains centered even when resizing

I have been attempting to center crop the responsive SVG image while resizing.

Even though I used

preserveAspectRatio="xMidYMax slice"
, the image width does not stay consistent with my screen size.

body{
  margin:0;padding:0;
}

.wrapper {
position: relative;
width: 100%; 
min-width: 100%;
vertical-align: middle; 
margin: 0;
}


.bg-svg {
display: inline-block;
position: absolute; 
top: 0; left: 0; 
width: 100%;
}
<div class="wrapper">
   <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  d="0px" y="0px"
     width="1920px" height="1080px" viewBox="0 0 1920 1080" preserveAspectRatio="xMidYMax slice" class="bg-svg">
  <rect fill="#DACFB9" width="1920" height="1080"/>
  <rect x="719" y="296" fill="#EF6544" stroke="#FFFFFF" stroke-miterlimit="10" width="482" height="482"/>
  <rect x="1438" y="296" fill="#AFFF84" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
  <rect x="1" y="296" fill="#7AEEFF" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
  <text transform="matrix(1 0 0 1 841 557)" font-family="'GothamBlack'" font-size="60">MIDDLE</text>
  </svg> 
</div>

I am striving to achieve a result similar to this Codepen demonstration, but without using a background image.

Answer №1

The key issue you were facing is that your SVG needed to include the attributes:

width="100%" height="100%"

This ensures that it fills the containing element properly. Additionally, there were some unnecessary CSS declarations in your code.

body{
  margin:0;
  padding:0;
}

.wrapper {
  width: 100%; 
  height: 100vh;
}
<div class="wrapper">
   <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%"
     viewBox="0 0 1920 1080" preserveAspectRatio="xMidYMid slice" class="bg-svg">
  <rect fill="#DACFB9" width="1920" height="1080"/>
  <rect x="719" y="296" fill="#EF6544" stroke="#FFFFFF" stroke-miterlimit="10" width="482" height="482"/>
  <rect x="1438" y="296" fill="#AFFF84" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
  <rect x="1" y="296" fill="#7AEEFF" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
  <text transform="matrix(1 0 0 1 841 557)" font-family="'GothamBlack'" font-size="60">MIDDLE</text>
  </svg> 
</div>

Answer №2

To achieve the desired result linked to, you need to use background-image. To ensure proper functionality, use this simplified version of svg. Ensure that you include the properties viewBox, xmls, and at least one of either width or height (specified as an integer without units). The svg will then function like any other background image. I am unable to demonstrate this directly here due to linking restrictions, but here is the modified SVG:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080">
    <rect fill="#DACFB9" width="1920" height="1080"/>
    <rect x="719" y="296" fill="#EF6544" stroke="#FFFFFF" stroke-miterlimit="10" width="482" height="482"/>
    <rect x="1438" y="296" fill="#AFFF84" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
    <rect x="1" y="296" fill="#7AEEFF" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
    <text transform="matrix(1 0 0 1 841 557)" font-family="'GothamBlack'" font-size="60">MIDDLE</text>
</svg> 

You can create a similar background effect using the following CSS:

svg {
  min-width: 100%;
  min-height: 100%;
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%,-50%);
  transform: translate(-50%,-50%);
}
 <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080">
    <rect fill="#DACFB9" width="1920" height="1080"/>
    <rect x="719" y="296" fill="#EF6544" stroke="#FFFFFF" stroke-miterlimit="10" width="482" height="482"/>
    <rect x="1438" y="296" fill="#AFFF84" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
    <rect x="1" y="296" fill="#7AEEFF" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
    <text transform="matrix(1 0 0 1 841 557)" font-family="'GothamBlack'" font-size="60">MIDDLE</text>
</svg>

If you save this configuration as an SVG file, you can easily apply it as a background image using background-image:

background-image: url(path/to/vector.svg) repeat 50% 50%;

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

Retrieve the API array index by checking the value of the 'Name' field

I am looking to compare the name of a button I click on with an array in order to find the matching name and then select the corresponding array number. Currently, I have a For loop that retrieves information from every team in the array, but I only requi ...

Fixing the error message "page attempting to load scripts from an unauthenticated source"

Can you help me troubleshoot an issue on my PHP page with ad scripts? I recently switched my site from HTTP to HTTPS and now the scripts are not appearing. Here is the error I found in the dev console: Failed to load resource: the server responded with ...

What is preventing me from setting a background image in Angular 13?

Trying a different approach based on advice from Stack Overflow, I attempted the following: <div [style.background-image]="'url(https://picsum.photos/200)'"></div> Unfortunately, this resulted in no effect and the image was ...

The carousel image slider seamlessly transitioning from the second image

I'm having an issue with the Carousel slider where it is overlapping the image from the second slide onwards. The first image loads properly, but subsequent images are not displaying correctly. Here's a reference image: CSS .slide { height: 473p ...

`Is it challenging to convert JSON into HTML, leading to undefined results?`

I am currently attempting to extract YAHOO data by utilizing getJSON and YQL. Although the connection is successful, I can retrieve the data and log it in the console. However, I am facing difficulties when trying to display this data on the JSP page I am ...

Utilizing the Command Line/Window feature within Visual Studio Code

As a newcomer to Visual Studio Code, I'm currently using the latest Version: 1.29.1. When I used Matlab, I had access to a script window for writing code, a Command Window for testing code snippets and viewing variable values, as well as a workspace ...

Which is more effective: coding with just plain JavaScript and CSS, or utilizing frameworks?

As a student, is it more beneficial to focus on utilizing pure JavaScript & CSS or frameworks? And which approach is best suited for the professional field? ...

Centering an image on a webpage using CSS

Here is the code I am using for displaying my image: return <div class="imgContainer"><img src={broomAndText} alt="broomAndText" /></div> In my css file, I have included the following styling: .imgContainer { tex ...

Utilizing CSS for Page Orientation

For my current project, I was tasked with designing a print view using HTML & CSS. This view is then converted into a PDF on the server and sent to an A5 printer for physical output. One of the specific requirements of this assignment is that the first pa ...

Build interactive web pages using Python scripts

By utilizing the Python scripts provided below, you can generate an HTML file with pre-set global variables (a, b, c, d). However, there might be instances when certain variables are not set globally, resulting in errors like "global 'a' is not d ...

Is it possible for the relative path of a gif image to become invalid when added to a div?

Question Context: In the view, I have a form that will show a loading 'spinner' gif when a user submits it. The Problem: If I place the spinner img element within its container div, the spinner is always displayed, which is not desired: https ...

Utilizing distinct useState for mapped elements

I am struggling to find a solution on how to pass specific useState states to respective mapped elements. export const Polska = () => { const [riverVisible, setRiverVisible] = useState(false) const [mountainVisible, setMountainVisible] = useState(fa ...

Navigating the screen reader with the cursor位

Site Design Challenge I recently discovered that the master/detail design of my website is not very accessible. The main view features a column chart where each column represents a different month. Clicking on one of these columns reveals details in a nes ...

What is the best way to show the initial image within every div that has the class name .className?

I am looking to only show the first image in each div with the class name "className." This... <div class="className"> <p>Yo yo yo</p> <p><img src="snoop.jpg" /></p> </div> <div class="className"> Hel ...

The variablewidth feature in Slick Carousel is malfunctioning

I've integrated slick slider 1.8.1 into my Rails app (v.5.2.0) and I'm encountering an issue with variablewidth set to true. My expectation was to achieve a layout similar to the example shown here: However, what's happening in my case is t ...

CSS not adding space between elements when using line breaks

I am trying to adjust the spacing between span lines to be 15px, however, I am encountering issues when using line-height. When measuring the space with a Chrome extension, it appears that the space is not actually equal to 15px. <div class="test"> ...

Elements with fixed positions in CSS overlapping one another

Hey there, I'm working on a navigation bar and using Jquery to resize elements for better website aesthetics. Instead of a traditional horizontal list, each button is created individually with images: <a href="#" class="button" id="home"><im ...

Tips for maximizing website performance on touch-enabled devices

When using a touch device such as an iPhone, iPad, or Android device, it can be challenging to accurately tap on small buttons with your finger. So far, there is no universal method in CSS media queries to detect touch devices. As a workaround, I check if ...

Deleting a row from a table when a similar element is found in another location

My webpage features a table list that showcases users linked to an organization: <script type="text/html" id="userListTemplate"> <div id="user_list_box"> <table class="list" style="margin-bottom: 15px;"> {{#Users} ...

What could be causing these transformed canvases to not display fully in Chrome at specific resolutions?

fiddle: https://jsfiddle.net/f8hscrd0/66/ html: <body> <div id="canvas_div"> </div> </body> js: let colors = [ ['#000','#00F','#0F0'], ['#0FF','#F00','#F0F&a ...