Align the content in the center vertically unless it is bigger

Currently, I am working on a small project involving a responsive website that utilizes the Skeleton responsive grid. To ensure that the content is centered vertically in the viewport, I am using jQuery.

<script>
$(document).ready(function(){                  
 $(window).resize(function(){
  $('.container').css({
   position:'absolute',
   left: ($(window).width() 
     - $('.container').outerWidth())/2,
   top: ($(window).height() 
     - $('.container').outerHeight())/2
 });    
 });
 // To initially run the function:
 $(window).resize(); 
});
</script>

However, I have encountered an issue where if the viewport size is smaller than the outer width of the container, it still applies absolute positioning.

My objective is to only apply absolute positioning to center the content in the viewport when the viewport is larger than the container's outer width. Is there a way to achieve this functionality with jQuery?

EDIT >>>>>

I am considering the following approach, but I am not entirely sure if it is correct:

$(document).ready(function(){
$(window).width();   // returns width of browser viewport
 $(document).width(); // returns width of HTML document

$(window).height();   // returns heightof browser viewport
$(document).height(); // returns height of HTML document

var width = $(window).width(); 
var height = $(window).height(); 

   if ((width >= 1024  ) && (height>=768)) {
 $(window).resize(function(){
  $('.container').css({
  position:'absolute',
  left: ($(window).width() 
 - $('.container').outerWidth())/2,
 top: ($(window).height() 
 - $('.container').outerHeight())/2
 });    
 });
 // To initially run the function:
 $(window).resize(); 
}
else {
//do nothing
}
});

Answer №1

To accurately determine the width of the browser viewport, you can use the following JavaScript code snippets:

$(window).width(); // provides the width of the browser viewport
or
$(document).width(); // retrieves the width of the HTML document
. These functions can be combined with $('.container').width().

To apply formatting based on width comparison, use the conditional statement:

if (compareWidth) {applyFormatting}

Answer №2

<script>
 $(document).ready(function(){                  
     $(window).resize(function(){
          // Check window size and adjust container positioning accordingly:
          if(($(window).width() > $('.container').outerWidth()) && ($(window).height() > $('.container').outerHeight()) ){
             $('.container').css({
                  position:'absolute',
                  left: ($(window).width() 
                     - $('.container').outerWidth())/2,
                  top: ($(window).height() 
                     - $('.container').outerHeight())/2
             });
          }else{
             $('.container').css({position:'relative'});
          }    

     });
     // Run the function on window resize:
     $(window).resize(); 
 });
</script>

Explanation: When the container's width and height are smaller than the window viewport, it will be positioned absolutely. Otherwise, it will use normal relative positioning.

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

Create a table within the B-Col element that automatically adjusts its size to match the column width using Vue-Bootstrap

Within my Vue component, I have the following code snippet: <b-modal ...> <b-row> <b-col sm="12"> <table > <tr v-for=... :key="key"> <td><strong>{{ key }}: </str ...

Seeking Answers About jQuery UI Themeroller

After designing a unique theme using http://jqueryui.com/themeroller/ and saving it, I have the theme downloaded. What is the next step to begin implementing the CSS for the theme? ...

Nested div within another div, shifting position relative to scrolling (React)

My goal is to create a unique effect where an object falls from the sky as the user scrolls down the page. The concept involves having the object div remain stationary in the center of its parent container, positioned 50 pixels from the top. However, when ...

Image floating next to a table

Trying to achieve something that I assumed would be straightforward, but CSS always has its surprises! The issue I'm facing is with an image floated to the left. Next to the image, I have a title, and below the title, but still alongside the image, I ...

Troubleshooting Dynamic Input Issue - Incorrect Appending Behaviour - Image Attached

I am working on a project that involves adding input fields dynamically using JavaScript. However, I've encountered an issue where the styling of the first input field is not applied correctly when it is clicked for the first time. You can see the dif ...

What is the process of connecting marionette rendered views to the DOM?

I am encountering a challenge with my simple setup using Marionette that I am trying to resolve. My issue lies within a view containing a collection: var MyItemsView = Marionette.View.extend({ template: "#some-template" }); var view = new MyItemsVie ...

Turbolinks gem causing ShareThis to malfunction

After adding the turbolinks and jquery-turbolinks gems to my project, I noticed that my ShareThis button no longer pops up when clicked. The ShareThis scripts currently included in my application.html.erb head are: <script type="text/javascript">va ...

Changing the border color of material ui Rating stars: A guide

I am struggling to change the border color of stars in Material UI Rating because my background color is black, making it difficult to see when the star is empty! Here's the code snippet: import Rating from '@material-ui/lab/Rating'; import ...

Disable sorting options in the Datatable ColumnFilterWidget

I'm currently working with datatables ColumnFilterWidget and I'd like to prevent the widget from sorting the values displayed in the select box. Despite trying the "bSort": false option of the ColumnFilterWidget, it doesn't seem to have any ...

relative font sizing based on parent element

My container is flexible in size, adjusting based on how the user moves elements around the screen. Inside this container, there is both an image and text. The image takes up 80% of the height of the container while the text should take up the remaining ...

Gaps separating frames

<!Doctype html> <html> <frameset rows="26%,24%,*" noresize border="0" frameborder="no" framespacing="0"> <frame src="frame_a.html" target="_self" name="logo" scrolling="auto"> <frame src="frame_b.html" target="_self" name="menu" ...

The header menu is not appearing on the gray bar in Internet Explorer

Having some issues with IE8, specifically on the website . The website header is not displaying correctly in IE8, but it works fine in Chrome and Firefox. Another issue is that the white area of the site is not 960px width as intended... ...

Utilizing Scrollify for seamless section scrolling with overflow effects

I have been experimenting with the Scrollify script (https://github.com/lukehaas/Scrollify) and facing an issue where my sections are longer than the user's screen, requiring them to scroll down to view all content. However, Scrollify doesn't al ...

A numerical input field that removes non-numeric characters without removing existing numbers?

Currently, I have implemented the following code: <input type="text" onkeyup="this.value = this.value.replace(/\D/g, '')"> This code restricts users from entering anything other than numbers into a field on my webpage. However, I hav ...

Using Ajax to implement a content slider with lightSlider

Seeking assistance in developing a dynamic content slider utilizing the LightSlider plugin. Currently, I have a script that fetches content from a database table (outputting JSON to HTML) and displays 6 div's of content per slide. However, I aim to di ...

Unable to receive JSON data from Ajax call

I'm encountering an issue with the WordPress feed in Json format (). When trying to read it using an ajax request, I am unable to retrieve any data in the success callback and instead receiving an error alert. Below is the snippet of my code: $.ajax( ...

Each slider only displays a single database entry

I have an array that retrieves testimonials from a database table and displays them using a foreach loop. I am looking to implement a slider that can fade in and fade out the results. Here is my database query: $showTestimonials = array(); $getTestimoni ...

What method should I use to target a specific element while loading content with AJAX in jQuery?

Is there a way to specify an element that will display content retrieved from a specific page URL within the code below? $(function () { $("a[rel='sort']").click(function (e) { //e.preventDefault(); /* if uncommen ...

Traverse an array in JavaScript and display the elements

I am new to JavaScript and struggling with a question. I have an array of 120 numbers that I want to loop through, printing out specific words based on certain conditions. For example, if a number is divisible by 3, I need to print "Go", if divisible by 5, ...

As I scroll down, my content hovers over my navbar

My website loads with everything in the right place, but as soon as I start scrolling, the content moves onto the navbar and hides at the top of the screen. I want the navbar to remain at the top of the screen at all times and have the content hidden under ...