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

The "add to cart" button is unresponsive

My issue is that the add to cart button on my website is not responding properly. I have implemented JavaScript on the add to cart button, where I have assigned an attribute called data-product with a value of {{product.id}}. var updateBtns = document.g ...

Steps to achieve overflowing text above the border-top just like with the border-bottom when setting the height to 0px

Can text be vertically aligned above the border-top in HTML when using height:0px, similar to how it can be done below the border-bottom? HTML: <ul id="experiment" style="background: #FFDD00;"> <li id="test1"><span class="v-align-bot"& ...

Equal-height columns in a responsive grid system

I'm currently facing an issue with a layout that seems simple I am working on a design featuring 4 headline boxes. In the "desktop" view, all 4 boxes need to be of equal height. The same applies when viewed across 2 boxes in the "tablet" mode. Howeve ...

Utilize MaterialUI Grid to define custom styles for the ::after pseudo-element

I came across a helpful article on Stack Overflow about Flex-box and how to align the last row to the grid. I'm interested in implementing it in my project: .grid::after { content: ""; flex: auto; } However, I'm not sure how to inc ...

Get rid of the margins on your Wordpress theme

Currently, my Wordpress site is using the Tesseract theme which can be found at (http:// instantiwebs . com) I am interested in removing the left/right margins on all elements, similar to what has been done on this website: . Interestingly enough, they al ...

Having trouble loading Yeoman Webapp SASS

Every time I try to build a web application using 'yo webapp', I encounter a 404 Error. GET http://localhost:9000/styles/main.css 404 (Not Found) I removed compass from the project, but that shouldn't be causing the issue, correct? ...

Rearrange the order of items in the fancybox gallery

Typically, fancybox displays items in the gallery based on the order they are added in the HTML code. Is there a way to customize the order of items when they are opened in the popup, while keeping the original order when displayed on the page? The solut ...

Using SVG background images in Internet Explorer versions 7 and 8: a guide to HTML, CSS,

I have created a unique SVG image to use as a background, but it's not displaying in Internet Explorer 8 and earlier versions. I tried using tools like or http://code.google.com/p/svgweb/, but they only support SVG for IMG and Object elements, not ba ...

Easily Update Your Div Content by Simply Clicking a Single Link/Button

I am in need of assistance here. My goal is to display dynamic content within a div. Below you will find the code I currently have: <script type="text/javascript"><!-- function AlterContentInContainer(id, content) { var container = documen ...

Postponing the activation of toggleClass in jQuery until the completion of a slide animation

Having some trouble with the jQuery delay() function. I'm using it to pause a toggleClass action until after a slideUp animation on one of my divs, but it doesn't seem to be working as expected. I want a bar with rounded corners that expands whe ...

What sets apart Firefox and Chrome when it comes to interpreting the widths of flex items?

Looking to create a column layout using flexbox with three divs that span the full width of their parent container while maintaining a single line height. If the content in the center div overflows, I want it to display an ellipsis at the end. Check out t ...

Changing background color during drag and drop in Angular 2: A step-by-step guide

A drag and drop container has been created using Angular 2 typescript. The goal is to alter the background color of the drag & drop container while dragging a file into it. Typescript: @HostListener('dragover', ['$event']) public onDr ...

Changing the color of Material UI pagination: a step-by-step guide

I have integrated Material UI to create a pagination bar for my website. While everything is functioning properly, I am looking to personalize the appearance. After reviewing their documentation, I tried implementing a theme but encountered an issue with c ...

Converting HTML to PDF using AngularJS

Can anyone help me with converting HTML to PDF in Angular? I have tried using the angular-save-html-to-pdf package from npm, but encountered errors. Are there any other solutions or custom directives available for this task? ...

Use JavaScript to add a div element to the page ten times every time the button is clicked

Here is the code I have written: $(document).ready(function () { $('<button class="btn more">View More</button>') .appendTo(".listing-item-container") .click(function() { $(this).closest(". ...

What is the best way to conceal a canvas or another item?

Within my main canvas, there are three smaller canvases and a text element. <canvas id="Background" width="350" height="300" style="border:6px solid black; position: absolute; left: 10px; top: 10px;"> </canvas> <canvas id="Canvas1" width ...

Height of list items in image gallery does not automatically readjust

I'm facing an issue regarding the height of an li element. Check out this CodePen link for reference. <div class="row fp-gallery"> <ul class="large-block-grid-4 medium-block-grid-4 small-block-grid-2"> <li> <a href= ...

Tips on automatically adjusting the width of a div to fit the content, maintaining center alignment, and ensuring the contents float to the left

I am facing an issue with a div element that has multiple children. My goal is to have the children neatly fit to the bottom left of the grid when the window expands, utilizing the next available space efficiently. However, as the div expands with the wind ...

Creating a customized design for your jQuery UI modal dialog box using CSS

I recently had to customize the jqueryui modal dialog in order to meet the standards set by my company. Currently, I am facing a cross-browser issue with the float and width of the input labels. You can view the sample website here: http://inetwebdesign. ...

Basic Jquery CSS style requests

Can you help me troubleshoot this issue? var hover = $('<img />').attr('src', hovers[i]).css('position', 'absolute') I'm having trouble getting th ...