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

How can I convert the left links in my navigation bar to a CSS drop-down menu to make it more responsive on small screens?

Here is the structure of my HTML (at the top): <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></s ...

Clicking on the anchor at the bottom of the page will smoothly navigate you to the top of the page

I added an anchor at the bottom of the page. I wrapped a group of buttons with the link so that when clicked, they trigger the assigned JavaScript and scroll to the bottom of the page. However, the buttons currently execute the JavaScript but then take you ...

What could be causing my websocket server to not properly serve my HTML page?

I'm currently facing an issue with establishing a web socket connection using NodeJS in my app.js file. Despite declaring a listener on port 8080, the connection is not getting established and no logs are being generated in the console. My goal is to ...

How to extract HTML elements using Selenium

<html xmlns:plm="http://www.plmxml.org/Schemas/PLMXMLSchema"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>View Health Report</title> </head> <body></body> </h ...

Having trouble showing table data in Angular

My goal is to showcase data from a table created using Spring-Boot Below is my model.ts: export class Quiz1 { QuestionId?: any; Question?: string; OptionsA?: string; OptionsB?: string; OptionsC?: string; OptionsD?: string;} He ...

JavaScript code encounters difficulties parsing HTML source

I'm attempting to reconstruct the WhateverOrigin service, which can be found at this link: Nevertheless, when I try running it in my web browser, this code that functioned perfectly with WhateverOrigin no longer functions properly with my imitation s ...

Navigational assistance on the keyboard - Improving Accessibility

My situation involves selecting an option from a dropdown menu on X-page, which triggers the opening of Modal-1 while disabling the background. If a selection is made within Modal-1, it leads to Modal-2. I am facing two issues/questions: Upon opening Moda ...

Tips for hiding a bootstrap modal in Angular4 when it has no content

I am currently working on an Angular 4 e-commerce application. One of the requirements is to hide a bootstrap modal when there are no products in the cart. When a user selects some products, they are added to the mycart modal screen. The user also has the ...

Guide on serving static HTML files using vanilla JavaScript and incorporating submodules

Is it possible to serve a static html file with elements defined in a javascript file using imports from submodules using vanilla JS? Or do I need bundling tools and/or other frameworks for this task? Here's an example code structure to showcase what ...

Is there a way for me to determine if I am accurately interpreting the content on websites?

I created this function to check for any changes on a website. However, I have noticed that it produces incorrect results when tested on unchanged websites. Can you help me identify the issue and determine if there is indeed a problem? Here's the code ...

retrieve the height value of a div element using AngularJS

I'm having trouble retrieving the updated height of a div using AngularJS. It seems to only provide the initial value and does not update as expected: vm.summaryHeight = $(".history-log-container").height(); console.log(vm.summaryHeight);//always dis ...

Avoid creating a line break directly after the header, however allow for a line break

I find myself in a scenario where I require a paragraph that has a specific format: An Emphasized Title Some relevant information regarding the subject... I am looking to insert a new line before the title, ensuring it seamlessly integrates with the re ...

Making the text gradually disappear at the bottom of a section using a see-through overlay, while ensuring the height remains within the boundaries of the section even

Trying to achieve a sleek fade-out effect at the end of a text section for a 'read more' indicator. I've been studying various tutorials, including this, and my current code is as follows: html <section> <p>Lorem ipsum dol ...

What is the best way to showcase a single <ul> list in an infinite number of columns?

Utilizing Django on the backend, I aim to showcase the list below in an unlimited number of columns with overflow-x: auto. <ul class="list"> {% for i in skills %} <li>{{i}}</li> {% endfor %} </ul> Example Result: 1 7 ...

Conceal certain digits of a credit card number in a masked format for security purposes

Is there a reliable method to mask Credit Card numbers in password format within a text field? **** **** **** 1234 If you are aware of a definitive solution, please share it with us. ...

The method window.scrollTo() may encounter issues when used with overflow and a height set to 100vh

Suppose I have an HTML structure like this and I need to create a button for scrolling using scrollTo. However, I've come across the information that scrollTo doesn't work well with height: 100vh and overflow: auto. What would be the best way to ...

Present XML data on an HTML page to generate interactive form features

I have an application that features a checkbox tree. I would like to automatically pre-select those checkboxes if the user had previously checked them. To achieve this, I receive XML data from my backend Perl script which contains information on which che ...

Using JavaScript, retrieve the ID of a child element by utilizing details about the parent element

I have implemented a JavaScript function that creates a div element. Within this div, there are multiple checkboxes as child elements. My goal is to use a loop to extract the ids of all these checkboxes. The div has been assigned to a variable named: o ...

What is the method for incorporating this effect into the final sentence of a text?

I am trying to create a unique design effect by applying a custom border to only the last line of text. You can see an example here. In this scenario, the target text is "2000 years old." (with that specific length) and not the entire width of the parent ...

I recently implemented a delete function in my code that successfully removes a row, but now I am looking to also delete the corresponding data from localStorage in JavaScript

I have successfully implemented a delete function in JavaScript that deletes rows, but I also want to remove the data from local storage. This way, when a user reloads the page, the deleted row will not appear. The goal is to delete the data from local s ...