Is there a way to adjust the height of a DIV based on the background image and keep the text centered at the same time?

Currently in the process of designing a landing page for my website, and I am interested in incorporating a Jumbotron to provide a more modern and tech-savvy touch. Successfully managed to center my text both horizontally and vertically, now looking into setting up the background image. Encountered an issue where I need the Div to adjust its height based on the background image while keeping the text centered. Below is a snippet of my HTML:

<div class="jumbo">
  <div class="jumboCon">
    <h1 class="centre">Kraft, unique</h1>
    <p>The best present is a special one</p>
    <div class="action">
      <p>Search!</p>
    </div>
  </div>
</div>

Additionally, here is the corresponding CSS:

.jumbo {
    width: 100%;
    background-image: url(../img/kraft.png);
}


.jumboCon {
    width: 50%;
    margin: auto;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    color: #fcfcfc;
}

After reviewing various questions and answers regarding this issue such as this one, the suggestion was to place the image directly in the Div, but that poses a challenge since I also need to center text within. Adding to the complexity, the dimensions of the image will vary since users will be promoting their own pictures.

I am aiming to achieve a similar effect as demonstrated on the Ghost website which you can view here. While not proficient in JavaScript, I'm confident in my ability to copy and paste code snippets if necessary. Appreciate any assistance!

Sincerely, Nick

Answer №1

When considering my comment regarding images with known ratios.

The concept involves adjusting the box and image to have the same ratio. Subsequently, the image is resized to fit 100% of the width using background-size.

A pseudo element with vertical padding in percentage will expand the box to maintain the desired ratio.

By utilizing a floating pseudo-element, text can be centered: DEMO

Furthermore, with an inline-block pseudo-element, content can be both centered and vertically aligned: DEMO

/* center & middle */
.jumbo {
  margin:auto;
  overflow:hidden;
  background:url(http://lorempixel.com/640/480/) no-repeat red;
  background-size:100% auto;
  text-align:center;
}
.jumbo:before {
  content:'';
  padding-top:75%;/* because ratio is 4:3 */
}
.jumbo:before , .jumboCon {
  display:inline-block;
  vertical-align:middle;
}

Note: The image will maintain its ratio, allowing the box to increase in height as needed, even if the screen or window ratio does not align perfectly.

Answer №2

For my latest project, I found a helpful guide that assisted me in creating the perfect layout. The article can be accessed here: http://css-tricks.com/centering-in-the-unknown/. What appealed to me most was its use of pseudo elements like :before, eliminating the need for extra markup on my page.

Incorporating the suggested changes from the article, I converted #jumbo to position: absolute; with full width and height dimensions. This adjustment allowed me to effortlessly center the element as per the article's instructions.

.jumbo {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: url(../img/kraft.png);
    text-align: center;
}

.jumbo:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

.jumboCon {
    display: inline-block;
    width: 50%;
    margin: 0 auto;
    color: #fcfcfc;
}

Answer №3

One way to achieve the desired effect is by using an img element to set the size of your div. Then, you can have a inner content div with a position:absolute and text-align:center, creating a full image background with a centered div in front.

For a visual example, check out this link: http://jsfiddle.net/T5M8B/

UPDATE:

To further enhance the design, you can add two more div's with a display:table effect to center it vertically. Here's the modified version: http://jsfiddle.net/T5M8B/1/

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

seeking a solution to simulate a variety of web browsers

Seeking a solution to preview my website on various browsers including IE7 and above, as well as different versions of Firefox. Although I am new to CSS, I previously tried installing software on my PC to assist with this task, which unfortunately caused ...

Pause and continue scrolling through the page with the push of a button

I have a question about a simple demo. I am looking to prevent scrolling when button1 is clicked, and then resume scrolling when button2 is clicked. Can someone guide me on how to achieve this? Check out the Fiddle here HTML: <input type='button& ...

Unable to retrieve the chosen option from the datalist

I am encountering an issue with a datalist where I can't seem to retrieve the value that is currently selected when a button is clicked. Despite following recommendations from various posts on Stack Overflow, my code still returns undefined. Interesti ...

JavaScript/CSS manipulation: The power of overriding animation-fill-mode

When animating text using CSS keyframes, I use animation-fill-mode: forwards to maintain the final look of the animation. For example: #my-text { opacity: 0; } .show-me { animation-name: show-me; animation-duration: 2s; animation-fill-mod ...

Styling the ::selection inline with CSS allows for custom

I have a div element that I would like to customize the text selection style for. Currently, setting the style using CSS works perfectly: <div>Text text here</div> <style> div::selection { background: #FFF; color: #0 ...

Ensure that the HTML image and text are positioned side by side, with the text appearing alongside the picture rather than below

Looking for a way to keep the text aligned to the right of an image, regardless of length? Check out this exercise: https://www.example.com/css/exercise-1 Is there a method to maintain the text layout next to an image while accommodating varying amounts o ...

Tips for stopping the textarea from moving around as you type and avoid it hitting the bottom of the page: Utilize JQuery and

As I type into the auto-sizing textarea, the text runs to the bottom of the page and causes it to dance uncontrollably with each key press. This forces me to constantly scroll down to see what's happening. How can I prevent this page dancing and keep ...

What is the best way to place multiple images on top of one another within a single div, and make them break apart with animation upon hovering?

HTML: <div class="mySlides"> <img src="1.jpg"> <img src="2.jpg"/> <img src="3.jpg"/> <img src="4.jpg"/> <img src="5.jpg"/> </div> CSS: .mySlides { padding-top: 25%; padding-left: 5%; ...

Dynamic Column Image and Text Display

I am working on a website where I am trying to have an image on the left and a paragraph on the right, but when the screen size is reduced, I need the layout to switch so that the image is at the top and the paragraph is at the bottom. Even though I have ...

Animating a Canvas to Follow Mouse Coordinates

I am looking for a way to animate a circle moving towards specific coordinates, similar to the game . I have attempted using the jquery animate() function, but it is too slow due to the constant updating of the target coordinates. Is there a faster metho ...

How can I use jQuery to create a new div element if it is not already present

I am familiar with how to add a class if it does not already exist, for example: $("ul:not([class~='bbox'])").addClass("bbox"); Alternatively, if(!$("ul").hasClass("class-name")){ $("ul").addClass("bbox"); } However, I am unsure how to c ...

What is the manual way to activate Ratchet's push feature?

I am facing an issue with a link that triggers a search function. Currently, the link is working as expected. However, I am having trouble getting the search to be executed by pressing the 'enter' button. Here is my code snippet: $('#sea ...

Ways to utilize jquery to limit the length of an editable div and prevent it from exceeding our specified restriction

Imagine a scenario where you have the following code snippet: <div id="editing" contenteditable onclick="document.execCommand('selectAll',false,null)">Put text here...</div> In this situation, let's say you want to impose a r ...

Database not receiving input data from AngularJS form submission

Having some trouble saving form data to the database using angularjs. Not sure what I'm doing wrong. Here's my HTML form: <form id="challenge_form" class="row" > <input type="text" placeholder="Challenge Name" ng-model="ch ...

I am unable to display the content even after setting `display: block` using the `.show()`

Hello there, I have attached my javascript and html code. While in debug mode, I can see that the CSS property 'display: none' changes to 'display: block', but for some reason, the popupEventForm does not open up. Any suggestions on why ...

What is the best way to deactivate a button when a certain input field is left blank?

I'm having trouble figuring out how to deactivate a button when specific input fields are empty, while others can remain optional for the process. In my course, we were taught to disable the button until all inputs are valid, so I'm a bit confus ...

Exploring Style Attribute Manipulation using vanilla JavaScript on Firefox

I searched for a similar question, but I couldn't find anything quite like it. I'm currently developing a JavaScript Slider plugin for various projects within our company. This requires me to manipulate styles on certain elements in the DOM. I&a ...

Tips for styling cells in a certain column of an ng-repeat table

I am currently facing an issue with a table I have created where the last column is overflowing off the page. Despite being just one line of text, it extends beyond the right edge of the page without being visible or scrollable. The table is built using th ...

Issues with the responsiveness of Bootstrap 4.5.0 grid system

While following a Django tutorial, I encountered an issue with Bootstrap cards and CSS styling. Using the latest version (Bootstrap 4.5.0), I noticed that my responsive grid was causing the cards to overlap as I increased the screen size. Comparing it to t ...

What causes a horizontal line to form when a user enters white space?

I have written a piece of code which seems to be causing an issue when running it. Whenever I input empty spaces, it results in creating a horizontal line. import React, { Component } from 'react'; export default class App extends Component { co ...