Ways to determine the height of a responsive div's background image

I have a container with a background image. Inside this container, there are additional elements like my navigation bar.

My goal is to make the container have the same height as the background image.

I've attempted the following:

.bg {
        width: 100 %;
        display: inline - block;
      }

      .bg::after {
        background: url('/images/desktop2.png') no - repeat center top;
        background - size: 100 % auto;
        content: "";
        opacity: 0.8;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        position: absolute;
        z - index: -1;
      }
<div class="bg">
        <div class="navigation"></div>
        <div>Other contents</div>
      </div>

      <div class="container">
        <div>First content</div>
        <div>
          <Second content</div>
            ...
        </div>

While this method has resulted in the bg div having the image's height, the container div ends up inside the background image.

What I actually need is for the bg div to only contain the navigation and other contents.

After that, the container should hold its contents separately.

Answer №1

To adjust the height of your container to match the aspect ratio of your background image, you can utilize a pseudo element and padding:

Here's an example:

.bg-ratio {
  background: url(https://baconmockup.com/1024/576) no-repeat red/* only to check ratio height */
  ;
  background-size: 100% auto;
  overflow: hidden;
  /* to see the floating pseudo */
  font-size: 5vmax;
  color: white;
  text-shadow:0 0 1px black;
}

.bg-ratio:before {
  content: '';
  float: left;
  padding-top: 56.25%;
  /* (576px / 1024px) x 100 */
}

body {
  width: 80%;
  margin: auto;
}
<div class="bg-ratio">
  <header>content in here</header>
  <main>
    <p>play full page and resize window's width</p>
  </main>
</div>

How to grow height of an element to match a ratio ?

Vertical margins or paddings in percentage value will be calculated from parent's width. padding-top : 100% will be equal to parent's width. When set on a pseudo element, an empty box will expand to be a square (ratio 1:1 ).

Source: https://www.w3.org/TR/CSS2/box.html#padding-properties

<length>

Specifies a fixed width.

<percentage>

The percentage is calculated with respect to the width of the generated box's containing block, even for 'padding-top' and 'padding-bottom'. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1.

Unlike margin properties, values for padding values cannot be negative. Like margin properties, percentage values for padding properties refer to the width of the generated box's containing block.


If the container spans the whole screen, you may use vw units through height or min-height and eliminate the need for the pseudo element.

.bg-ratio {
  background:
  url( https://baconmockup.com/1200/100)
  no-repeat
  red /* only to check ratio height */;
  background-size: 100% auto;
  height: 8.33vw; /* (100px / 1200px) x 100 */
}
body {
  margin: auto;
}
<header class="bg-ratio">
  <div>content in here</div>
</header>
<main>play full page and resize window's width</main>

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

I'm wondering if anyone has any insights as to why the CSS rule `body{ overflow: auto;}` is not functioning properly for me. Despite my attempts of adding a class to the body tag and

I am facing an issue where adding body tags to my code in Visual Studio code does not yield the desired results. Interestingly, it doesn't seem to be a syntax error in CSS. body{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI&apo ...

Display the initial three image components on the HTML webpage, then simply click on the "load more" button to reveal the subsequent two elements

I've created a div with the id #myList, which contains 8 sub-divs each with an image. My goal is to initially load the first 3 images and then have the ability to load more when clicking on load more. I attempted to follow this jsfiddle example Bel ...

Concealing a button once the collapse feature is toggled in Bootstrap

The following code snippet from the bootstrap website demonstrates how to use collapse functionality: <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> Link with href & ...

Disabling the scrollbar in Selenium screenshots

When using Chromedriver to capture screenshots of webpages, my code effectively does the job. However, I am now facing an issue with removing the unsightly scrollbars from the image. Is it feasible to inject CSS into the webpage in order to achieve this? W ...

What is the functionality of this pseudo element?

I am interested in understanding the purpose of the pseudo element and how it affects the layout without altering the existing markup. Check out the code demo div{ border: 1px solid #000; height: 300px; } div:before{ content: ""; ...

Position a Paper component in the center of a div

I'm having trouble centering my <Paper> element inside a div. Can anyone help me with this? I have placed both the <Paper> and <RaisedButton> elements inside the div and applied the following CSS: .timerArea { text-align: center; ...

Angular 7 - Customize Mat-select-value color depending on a specific condition

One issue I am facing is changing the color of a selected value in a mat select based on a condition. This change should be visually apparent to the user. Although accessing mat-select-value from the styles is possible, implementing a condition using ng-cl ...

The child element is bigger than its parent due to the maximum height set. There is no visible overflow

My goal is to create a parent element with a maximum height, and have a child element fill this parent. If the content in the child exceeds the parent's dimensions, a scrollbar should appear. I attempted to achieve this by: div.parent { max-hei ...

Transforming HTML into a Console Experience (Angular 16)

I'm experimenting with creating a console/CLI style experience using HTML. The goal is to have the input fixed at the bottom of the window, while commands and output rise up from the bottom and eventually disappear off the top of the screen, enabling ...

"Enhance User Experience with a Bootstrap Dropdown Button Offering Block Level Function

I'm attempting to modify a bootstrap 3 dropdown button to fully utilize the width properties of .btn-block class. It appears that the dropdown button does not respond in the same way as regular buttons. Below is my current code: <div class="row"&g ...

Dynamic Font Formatting in Rails Table Based on Conditions

I need to customize the font color of dynamic values based on the state_id. If incident.state_id = 1, the font should be red; if incident.state_id = 2, it should be yellow; and if incident.state_id = 3, it should be green. incident.state_id = 1 : state.na ...

Add a decorative frame around the heading and text block

I'm looking to encase both the header and paragraph in a single border. Right now, they each have their own separate borders. How can I combine them into one? <style type="text/css> h1, p { font-family: consolas; border: 2px solid #73AD21; bor ...

Keeping the header in place: fixed positioning

This particular situation is quite challenging for me. I have a webpage that requires horizontal scrolling. There is a menu at the top of the page that needs to remain centered on the page at all times. Even with the use of jQuery, I am uncertain how to ac ...

Navigating on the horizontal axis within a container with overflow properties

I am trying to insert multiple children-divs into a parent-div. The parent div has a fixed width. The children are set to float left and will overflow the container. I need the ability to scroll along the x-axis. However, when I attempt to do this, the c ...

What is the best way to distribute components with varying cell heights?

I am currently working on creating a user interface layout with components that need to be arranged in a specific order, as depicted in the accompanying image. My task involves developing a Material UI Dialog within a React application based on the design ...

Is it possible to create an image or logo that moves in sync with the user's scrolling

Having trouble articulating this question, but I'm trying to replicate the logo in the top right corner of this website: I want the logo to move along with the user as they scroll down, remaining visible at all times. Any ideas on how to achieve this ...

Update the default arrow icon in the expand/collapse navigation bar

I need help changing the downward arrow in the code below to a fontawesome icon. I'm unsure about how to: 1. Remove the default arrow on the right of the parent node. 2. Use "+/-" symbols to represent the collapse state. It seems that the onclick c ...

Display an image when the link is hovered over within a table

I'm looking for a way to display a scanned receipt image when hovering over a link within a table. I've written some code but it's not working as expected. Can anyone help me figure out what's wrong? Here is the current state of my cod ...

How can I use XPATH to target a div after choosing a nested element?

I had the task of creating a universal identifier to locate a dropdown menu following a label. There are 10 different forms, each with a unique structure but consistent format, which means I cannot rely on specific IDs or names. Instead, my approach was to ...

IE and Chrome are experiencing issues where the radio buttons are disappearing

Here is the style sheet code: select,input ,td a {border:1px solid green; width:25%;height:25px;font-size:20px;margin- left:.1em;} input.myradio {border:none;width:0%;height:0%;font-size:0%;} And here is the corresponding HTML code: <td><inpu ...