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

What are the best situations to utilize bootstrap and when should you avoid it?

When it comes to web development, there is often a debate on whether to use Bootstrap or custom CSS for designing a website. For my school project, I am tasked with creating a homepage and contact page using Bootstrap primarily. However, we are also requir ...

Unable to choose the specific div element within the container that has an inset shadow applied by utilizing Pseudo

It seems that I am encountering an issue when trying to select the div elements within a container that has a defined shadow using pseudo elements ::before OR ::after. Once the shadow is applied, the div elements become unselectable. Please refer to the c ...

The absence of an eye icon in the password field when using bootstrap 5

I'm having trouble positioning the eyeball icon to the right side of my form when using Bootstrap v5 and FontAwesome v5. Instead, the password field is being shifted further to the right compared to the username field, and the eye icon is not displayi ...

Is it possible to execute this animation with a single click for repetitive playback?

CODEPEN const btt = document.querySelector('.btt'); btt.addEventListener('click', function(){ this.classList.toggle('anime'); }); Is there a way to achieve the desired effect with just one click? ...

Managing the width of an HTML table column based on its text content dynamically

Here is an example of an html table : <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="480px" class="societe" ><div style="float:left;font-size:12px;padding-top:2px" ><?php echo $_SESSION ...

Utilizing JQuery for a smooth animation effect with the slide down feature

I have a question about my top navigation bar animation. While scrolling down, it seems to be working fine but the animation comes with a fade effect. I would like to achieve a slide-down effect for the background instead. Since scrolling doesn't trig ...

Resolve the issue of Dojo images not appearing on a div in Internet Explorer

I am trying to incorporate images into a dojo chart using the given code: var l_images = ["images/clearnight.png","images/clear.png","images/partlyCloudy.png","images/cloudy.png","images/showers.png","images/rain.png","images/thunderstorms.png","images/ic ...

Prevent tooltips from displaying outside of an HTML table by using the overflow hidden property for horizontal scrolling

TL;DR: Struggling to position and display tooltips in a table due to the constraints of overflow: hidden. An example has been created to demonstrate the issue with tooltips not displaying correctly within a table. The problem arises because the table nece ...

Adjust the dimensions of the embedded Google document

Currently, I am in the process of developing a website for my initial client and I'm encountering some difficulty in adjusting the size and background color of an embedded google doc. If anyone could provide assistance, it would be greatly appreciated ...

Angular directive specifically meant for the parent element

I am working on a directive that I need to apply to a specific div element without affecting its child elements. The goal is to make the main div draggable, so that when it moves, its child divs move along with it. However, I do not want the child divs to ...

Interested in compressing CSS and JavaScript using PHP, but uncertain about the impact on performance and the best methods to implement it?

My current approach involves using PHP to combine multiple css (or js) files into a single file, while also compressing the content using GZIP. For example, the HTML page makes calls to resources like this... <link rel="stylesheet" href="Concat.php?fi ...

What is the best way to embed a section of another website within an iframe and seamlessly guide a user to complete a purchase using a shopping cart?

Seeking advice on how to improve the functionality of my website. Currently, the domain I'm focusing on serves as a landing page, redirecting users to another site for purchases. I've built a separate website for this domain in order to establis ...

Code Snippet: Adjust Table Column Alignment using CSS

Apologies for the basic question, as I am new to CSS. Below is the UI that I am working with: https://i.stack.imgur.com/crAYE.png Here is the code that corresponds to the UI: <div class="row centered-form center-block"> <div cla ...

What is the best way to adjust a horizontal list of inline elements to stack vertically when the div container is resized?

Here is the issue I'm facing (notice how the yellow tiles are overflowing): (view image here) because my reputation points are not enough. The screenshot above illustrates how the small yellow rectangles are extending beyond the boundaries of the gr ...

What is the best way to position an image in the center over a video using HTML and CSS?

I am currently developing a website with a background video and I want to overlay a company logo on top of it while keeping it centered. My coding language of choice for this project is using HTML and CSS. Here's the HTML code snippet I have for this ...

Incorporate a 'Select All' functionality into ion-select by adding a dedicated button

Looking for a way to set custom buttons on ion-select through interfaceOptions in ionic 4? HTML <ion-item> <ion-label>Lines</ion-label> <ion-select multiple="true" [(ngModel)]="SelectedLines" [interfaceOptions]="customAlertOption ...

The content in the flex box item with horizontal scroll is overflowing beyond its boundaries

I am working with a flex box container that contains two child elements: a left side and a right side. I want the right side item to have a horizontal scrollbar in order to fit its content. .container { display: flex; overflow: hidden; height: 300 ...

Designing a scrollbar for a tr element using HTML and CSS

I am struggling to create a scrollbar for the inner table that is not being displayed within its container. The container has a yellow background while the table itself is blue. My goal is to have a scroll bar specifically within the table. For more info ...

Caution: The `className` property does not align with Material UI css which may cause issues upon reload

https://i.stack.imgur.com/MxAiY.png If you are facing the error/missing CSS, check out this video for a visual representation. While older versions of similar questions exist on Stack Overflow such as React + Material-UI - Warning: Prop className did not ...

The code in check.js causes a square of dots to emerge on the screen in Skype

Trying to add a Skype call button to my page has been successful, but there's one issue - a pesky white dot keeps appearing at the bottom of the footer. The script source I used is as follows: <script src="http://download.skype.com/share/skypebu ...