Is it possible to center Div/Img elements both vertically and horizontally over a background of a cover size?

^Read my jsfiddle link^ I have a small jq script that adjusts background image size based on viewport dimensions. My issue is with a div (.png) that needs to be centered vertically and horizontally on the background, no matter the screen size. I've tried various units and values but it's not working well in mobile portrait or landscape. Is there a universal solution or should I use media queries?

Appreciate your help!

<div class="hero"> 
<img class="logo" id="biglogo" src="http://www.seomofo.com/downloads/new-google-logo-knockoff.png">

       </div> 

$(document).ready(function () {
  $(window).bind('resizeEnd', function () {
    $(".hero").height($(window).height());
  });

  $(window).resize(function () {
    if (this.resizeTO) clearTimeout(this.resizeTO);
    this.resizeTO = setTimeout(function () {
      $(this).trigger('resizeEnd');
    }, 300);
  }).trigger("resize");
});
/////
window.addEventListener("load", function(){
    var load_screen = document.getElementById("load_screen");
    document.body.removeChild(load_screen);
});

.hero
{   
    background-color: black;
    background-image: url(https://unsplash.imgix.net/photo-1419064642531-e575728395f2?q=75&fm=jpg&s=490dffe2e11f468947891ab40651e176) ;
    -moz-background-size: cover;
    -o-background-size: cover;
    -webkit-background-size: cover;
    background-size: cover;
    position: relative;
    background-position: 50% 50%;
}

#biglogo {
    display: block;
    position: fixed;
    max-width: 50%;     
    margin: 25% 25%;  /*??*/
    z-index: 5;
} 

Answer №1

It's been a while since I've worked on something like this, but for fixed elements, you'll probably need to add the following code at the end of the snippet above.

width: 50%; /*??*/
height: 25%;
margin-top: 50%;
top: -25%;
margin-left: 50%;
left: -25%;

Check out the updated fiddle for reference.

Edit: Based on a comment, here's an improved version with a wrapper class that can assist in positioning the image. View the new fiddle for more details.

Answer №2

The most convenient method to accomplish this task is by utilizing the transform property, which is widely supported in modern browsers today (Can I Use)

#biglogo {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    transform-style: preserve-3d;
    width: 100%;
    height: auto;
    max-width: 200px;
}

http://jsfiddle.net/3pwpny33/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 to display an image in a pop-up with a title

I am currently using the Bootstrap framework and I am trying to create a popup image with a title, but it only shows the image. I am not sure how to add code in JavaScript to display the title as well. Can someone please assist me? Here is my code: Javas ...

Reflections on the Javascript Prototype Design Pattern

After using a Javascript revealing module pattern, I'm now transitioning to a new approach which seems to be working. However, I'm not entirely sure if I'm following the best practices. Specifically, I want to know if my method of preserving ...

Verification of phone numbers in HTML

Currently, I am facing a dilemma while working on an HTML website. The client's requirement is to allow only numerical phone numbers without any alphabetic characters. The condition set is that the phone number field should accept and submit a phone ...

Identify the position of a mouse click event when dots overlap

Experience this live demo on CodePen by visiting it here. 1) When you click on the grid, a first red point will be added. 2) Click on the grid again to add a second red point. 3) By clicking back on the first red point, you may notice that the coordinat ...

Implementing CSS keyframes when a specified PHP condition is satisfied

I am looking to implement an opening animation on my website that should only play when a user visits the site for the first time. I want to avoid displaying the animation every time the page is reloaded, so it should only run if a cookie indicating the us ...

jQuery has a problem with the $.each method

I've created a function that checks elements with the class name .sitem. If any of these elements have a blank value, it should return an error message. Otherwise, the code should proceed as normal. if($(".sitem").each(function(ss, element) { if($(t ...

Suggestions for automatically adjusting the height and width of a div containing z-indexed content

I'm attempting to automatically adjust the height and width of the parent div that contains three stacked images, but the parent is not adjusting to the dimensions of the content. Even when the div and the last image are on the same z-index, it's ...

Tips for ensuring that a child div expands to the full dimensions of its parent div

Hi there, I'm currently facing an issue with making my child div expand to the height of its parent div. Below is the CSS for the parent div: #wrapper #content { border: 1px ridge #999; height: auto; min-height: 1000px; width: 1100px ...

A guide on choosing a custom button color and automatically reverting to its original color when another button is clicked

I have a collection of 24 buttons, all in a dark grey (#333333) shade. Whenever I click on one of the buttons, it changes to a vibrant blue color (#0099ff), which is functioning correctly. However, when I proceed to click on another button, the previous ...

What's wrong with this old jQuery code?

After stumbling upon this page: Page I was thrilled to find exactly what I was looking for. However, after copying the code, it doesn't seem to work. $(function() { var scntDiv = $('#p_scents'); var i = $('#p_s ...

Initiating an AJAX call to the server-side script (controller) to fetch the current server status

Looking to retrieve a server-side response for a button on a Twig page. For example, there are two buttons on the page - ON/OFF Upon loading the page, it should query the server (specifically Elasticsearch database) to determine if either button should b ...

"Identifying elements in CSS that do not have any adjacent text elements

I need help identifying a CSS selector that can differentiate between the <var> tags in these two distinct situations: <p><var>Foo</var></p> And <p>Some text <var>Foo</var> and more text</p> Specifi ...

Exploring XML with Jquery

Looking for assistance with parsing my XML Feed: Struggling to utilize JQuery to extract and display the data in HTML. Despite searching on Google, I haven't found a satisfactory solution yet. With numerous elements in my XML, it's proving to b ...

Storing multiple values of dynamically added elements in a single variable and accessing them within a function

Is it possible to store multiple values into a single variable and then access them in a setTimeout function? $(document).ready(function (){ div ({'div':'#noo','auto':'true','pos':'top',' ...

The issue arises when trying to apply CSS and minified JavaScript after adding new data in jQuery Mobile

I am having an issue with adding data and displaying it on a list. The problem arises when I add data through AJAX. In the success function, after showing the alert "successfully added", I used location.reload(), which takes me to the homepage (div tag dat ...

Error message occurs in jQuery form when optional fields are left empty, displaying a "missing ) after argument list" notification

I've encountered an issue with my form that submits to a jQuery plugin I developed. Until now, everything worked smoothly, but when I added optional fields to the form, things started going wrong. The input text fields in the form are initially popula ...

Positioning a div around a multi-layered canvas for a centered effect

I am looking to create a unique HTML5 canvas setup where multiple canvases are stacked on top of each other to allow for rendering with different layers using JavaScript. The challenge is to have these canvases centered both horizontally and vertically on ...

Prevent line breaks caused by the span tag in Bootstrap 5

I have been attempting to use white-space:nowrap; to prevent the span tag in this text from causing a line break, but so far I have not been successful. The class styles used here are all standard Bootstrap 5 CSS class styles. On wider screens, the time i ...

Launching the col-sm bootstrap class at 768px screen size: Tips and tricks

Is there a way to change the default screen size implementation of the bootstrap class col-md from 768px to 576px so that the class col-sm is implemented at that screen size instead? Here are the current defaults: Extra Small (<576px) .col- Small (> ...

What is the best way to expand the size of the pagination buttons in a primeng table?

My primeng table is quite large: <p-table #dt [value]="artefacts" [columns]="cols" [paginator]="true" [rows]="numberRows" [tableStyle]="{'table-layout':'auto'}"> With so many entries, the table spans over 100 pages. However, the ...