What is the correct way to apply background-position percentage in this situation?

This problem has got me at my wit's end.

Imagine a series of divs lined up horizontally. Each one is sized as a percentage of the total width, but that total width is unknown.

For instance:

---------------------------------
|     |     |            |      |
---------------------------------
0%   20%   40%          80%    100%

Now, I need to set a background image that spans across all the divs. However, each div might have different requirements for how the background image should be positioned and its size.

So, the first div (0% - 20%) needs a background-width of 500% and a background-position of (0, 0)

The second div (20% - 40%) also requires a background-width of 500% and a background-position of (25%, 0) (more details on this later)

The third div (40% - 80%) should have a background-width of 250% and a background-position of (~66.66%, 0)

Finally, the last div (80%-100%) will again have a background-width of 500% with a background-position of (100%, 0)

It might seem like a trivial issue, but I'm struggling with calculating the correct values for these background-positions based on the div's width and position in the strip. Even though I have a rough understanding of percentage positioning, I can't quite wrap my head around it. Any guidance on this matter would be greatly appreciated.

Edit: After some trial and error, I believe I've cracked the code on this. However, before I share my solution, I'd like someone to verify its accuracy because my brain is too fried to grasp the reasoning behind it at this moment. Perhaps after some rest, I'll try to comprehend it myself. Here's how I managed to calculate the correct values:

background_position_x = div_strip_position_x + div_width * div_strip_position_x / (100 - div_width)

(All values are in percentages)

Answer №1

Using percentages in background-position:

To determine the background position, subtract the background image size from the background positioning area size. The size refers to the width for horizontal offsets and height for vertical offsets.

For more information on background positioning, visit this link.

.container {
  position: relative;
  display: block;
  width: 100%;
  font-size: 0;
}

.container>div {
  display: inline-block;
  height: 200px;
  background-repeat: no-repeat;
}

.container#example1>div {
  width: 50%;
  background-size: 200% 100%;
}

.container#example2>div {
  width: 33.33%;
  background-size: 300% 100%;
}

.container#example3>div {
  width: 25%;
  background-size: 400% 100%;
}
...

Lets take a closer look at example3.

The formula to calculate the background-position for each segment involves using,

100% / (segmentID * (numberOfSegments -1))

In this particular case, there are 4 segments in total we need to consider.

  1. 100% / (0 * (4-1)) == 0%
  2. 100% / (1 * (4-1)) == 33.33%
  3. 100% / (2 * (4-1)) == 66.66%
  4. 100% / (3 * (4-1)) == 100%

This calculation method is effective when

background-size: width == numberOfSegments * 100%
.

Answer №2

It seems that when it comes to background-positioning, the positioning is relative to the div itself rather than its parent container. To achieve the desired effect, you may need to use 0 for X or a negative value to create an offset so the image aligns with the parent's X=0 coordinate. It's important to consider how box-sizing will impact these values.

Depending on your specific project requirements, you could explore using CSS3's calc function or implementing a JavaScript/jQuery solution.

For additional insights and guidance, I discovered some informative resources:

  • Exploring ways to position a background image in relation to the center of an element
  • Methods for offsetting a background image from the right using CSS
  • Insights into understanding percentage-based background positioning in CSS

Additionally, check out this MDN article for further information on background positioning.

Answer №3

First, group them within a parent div element. Next, style their displays to be "inline-block" with a vertical alignment of "middle." Then, add a background image to all of them. Finally, customize the background size and position for each individual item.

.row-1{
  display:block;
  font-size:0;
}
.row-1 > div{
text-align:center;
height:20px;
display:inline-block;
vertical-align:middle;
background: url('http://www.imagestowallpapers.com/wp-content/uploads/2015/12/Background-Image-CSS4.jpg') no-repeat center center fixed;
    background-size: cover;
}
.w20{
   width:20%;
   background-color:red;
   font-size:13px
}
.w40{
   width:40%;
   font-size:13px;
}
.w20.first{
    background-position:0 0;
    background-size: 500%;
}
.w20.second{
   background-position:25% 0;
   background-size: 500%;
}
.w20.third{
   background-position:66.66% 0;
   background-size: 250%;
}
.w20.fourth{
   background-position:100% 0;
   background-size: 500%;
}
<div class="row-1">
  <div class="w20 first">1</div>
  <div class="w20 second">2</div>
  <div class="w40 third">3</div>
  <div class="w20 fourth">4</div>
</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

Ways to disable mousewheel function in jQuery

I am trying to deactivate the mouse scroll in jQuery and successfully did so, however, I encountered this error message jquery.min.js:2 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See Thi ...

Showing a 2D array in HTML using ngFor loop

I need to display a list of arrays in an HTML p-table. Here is the array list: [Array(2), Array(2), Array(2), Array(2), Array(1)] 0: (2) ["abc", "def"] 1: (2) ["ghi", "jkl"] 2: (2) ["mno", "pqr"] ...

Creating an interactive date selection feature with a calendar icon in MVC 5

I currently have a textbox that displays the datepicker when clicked. However, there is now a requirement to add a calendar icon inside the textbox. The datepicker should be displayed when either the calendar icon or the textbox is clicked. Below is the co ...

Use the controller to set the body's background image

Seeking help to update the image URL within the CSS code snippet provided. I would like to accomplish this from the controller and can work with either LESS or SCSS. Is there a solution for this? .background{ height: 100%; width: 100%; backg ...

Update the class of pagination to "active" using jQuery

I need assistance with pagination. Here's the code I have so far: <?php for($i = 1; $i<=10; $i++){ ?> <a class="pagenumber" href="?p=<?php echo $i; ?>"><?php echo $i; ?></a> <?php } ?> What I want to d ...

Should font size, line height, and font-family be declared to the body before or after the CSS reset?

Let's say I am using the Eric Meyer Reset and I need to apply a style to the body element. body { font: 100%/1.5 "Helvetica Neue", Helvetica, Tahoma, Arial, sans-serif;*/ } Should I place this before or after the reset CSS? html, body, div, span, a ...

Fixing Sticky Navigation Bar on Scroll (JavaScript, HTML, CSS)

I'm working on this site as a fun side project, but I've hit a roadblock. The sticky nav bar I implemented jumps when the user scrolls down far enough. Despite reading through other discussions, I can't seem to figure out the solution. I su ...

Ways to extract a specific line of text from HTML code

Can someone help me extract a specific line from an HTML code using Python? For instance, in this website: The snippet of code is as follows: var episodes = [[8,54514],[7,54485],[6,54456],[5,54430],[4,54400],[3,54367],[2,54327],[1,54271]]; I am lookin ...

What is the best method to exclude the <a> tag when displaying content in HTML?

Is there a way to hide the link within an a tag when printing? .p { display: none; } @media print { .p { display: initial; } .np { display: none; } } <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css ...

Unable to display background image on Webpage due to blank page issue while uploading it with HTML and CSS

I've been attempting to build a webpage with an image as the background, but I seem to be facing some issues. Instead of seeing the desired image, all I get is a blank white page. The folder named "images" is located in the same directory as my HTML a ...

What is causing the divs to remain stationary instead of floating away with BootStrap?

My divs aren't aligning properly as expected when using the BootStrap Grid System. For example, if I have 4 columns and then another 2 columns, the second div should take up the next 4 columns but instead it's appearing below in the same column r ...

Utilizing JavaScript to present JSON data in HTML tables across various sections of a website

Utilizing JScript to retrieve data from a JSON API URL, I have incorporated the data in the JSON file displayed below - containing information on 8 horse races with details like Horse number, Horse name, and their odds. My goal is to create a Jscript code ...

Modify the background color of each word within the search bar

I've been attempting to colorize each word using jQuery and give them a colored background. I came across a solution, but it only seems to work for the HTML content, not the input field in the search bar. Below is an example of what I found: HTML So ...

"Troubleshooting: jQuery Find function not functioning correctly with HTML template

I am having trouble with a Shopify liquid code that I am trying to load into an HTML template <script type="text/template" id="description"> <div class="product-ddd"> {{ product.description }} </div> ...

Rotate images every 5 seconds, pulling them directly from the server

I am looking to update the users every seven seconds on my website. To do this, I need to retrieve all user information from the server using JavaScript. What is the most efficient way to accomplish this task? My initial thought is to send an HTTP request ...

Is there a way to position the icon in the top left corner within the image using Vue and CSS?

I am currently working on a Vue project and I am attempting to create a row of images with an icon positioned at the top left corner of each image. Here is my code snippet: <div v-for="(image, index) in images" :key="index" class=&q ...

Nested Divs in CSS

I'm really struggling to get a div to display under another div in the way they usually do. Currently, I am using MaterializeCSS for my layout setup: <div class="container valign-wrapper"> <div class="customClass"></div> &l ...

Using jquery to toggle active nav links in Bootstrap

I'm currently working on integrating a jQuery function to automatically update the active status of the navigation links in my Bootstrap Navbar. The structure involves a base HTML file that extends into an app-specific base file, which is further exte ...

Forming a header area by utilizing a 960 Grid container

I'm in the process of designing a website utilizing the 960 Grid system. The header consists of three parts: the logo, the navigation, and the login form. I've implemented media queries to center both the logo and the login section when the pag ...