Align div in the center vertically if its height is smaller than the height of the browser window (

I'm currently utilizing CSS bootstrap 4 to create a layout with multiple columns per row inside a container. Depending on the screen size, these columns may stack on top of each other, causing the container to become taller and sometimes exceed the visible area, requiring scrolling. I'm trying to find a solution that addresses both of the following scenarios:

  • If the container is shorter than the browser window height, center it in the middle of the screen
  • If the container is taller than the browser window height, do not center it (to prevent it from going off-screen)

While I have code to center the container, when the content exceeds the screen height, it simply extends beyond the view and cannot be scrolled like a regular page.

Here's my HTML structure:

<div class="container centered" style="width: 100%">
    <div class="row justify-content-center">
            <div class="col-8" id="main">
                Text<br>
                Text<br>
                Text<br>
                <!-- Add more lines here if needed -->
            </div>
    </div>
</div>

And this is my CSS styling:

html,
body {
  width: 100%;
}

body {
  display: -ms-flexbox;
  display: flex;
  -ms-flex-align: center;
  align-items: center;
  padding-top: 40px;
  padding-bottom: 40px;
  background-color: rgb(0, 0, 0);
}

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

#main {
  background-color: rgb(30,29,38.3);
  border-radius: 6px;
  box-shadow: 0 0 30px rgb(25, 25, 35);
}

Answer №1

<section class="d-flex justify-content-center align-items-center"></section>

(alternatively)

     `.container
      { 
        display:flex;
        justify-content:center;
        align-items: center; 
        height: 100vh;
      }`

Answer №2

Try this CSS solution which should effectively resolve your issue. Feel free to insert additional text lines between the first and last ones to test it out:

*{
  box-sizing: border-box;
}
body {
  /* important styles */
  display: grid;
  align-items: center;
  min-height: 100vh;
  overflow-y: auto;
  /* important styles */
  background-color: rgb(0, 0, 0);
  margin: 0;
}

.centered {
  /* important styles */
  display: grid;
  align-items: start;
  /* important styles */
  padding: 1em 2em;
}

#main {
  background-color: rgb(30,29,38.3);
  border-radius: 6px;
  box-shadow: 0 0 30px rgb(25, 25, 35);
  color: white;
  padding: 1em;
}
<div class="centered">
      <div id="main">
          First Text<br>
          Text<br>
          Text<br>
          Text<br>
          Text<br>
          Text<br>
          Text<br>
          Last Text<br>
      </div>
</div>

Explanation: The body now has a grid display with its children vertically centered. Additionally, the ".centered" element is aligned at the top vertically with a grid display.

Answer №3

When the position of centered is fixed, it is taken out of the normal page flow, preventing the page from scrolling properly. A better way to center it would be:

body {
  display: -ms-flexbox;
  display: flex;
  -ms-flex-align: center;
  align-items: center;
  background-color: rgb(0, 0, 0);
  justify-content: center;
  min-height: 100vh;
}

https://example.com/qPnWgzLm20

Alternatively, you can achieve the same result using Bootstrap classes:

<body class="d-flex align-items-center justify-content-center min-vh-100">
    <div class="container">
        This content is centered...
    </div>
</body>

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

$_POST is unable to read POST parameters when using AJAX

I've been facing an issue with sending data to my PHP script. Interestingly, everything works smoothly when using POSTMAN and the results are displayed correctly. However, when attempting to send the data through AJAX in my HTML project, the PHP scrip ...

Issues with Bootstrap Contact Form submission

I found a helpful tutorial for creating a form at the following link: After following the tutorial, I added these scripts to the bottom of my contact form HTML: <script src='https://code.jquery.com/jquery-1.12.0.min.js'></script> ...

Once the if condition is implemented, the functionality of the toggle button ceases to operate

Take a look at this demo link: http://jsbin.com/labuxuziraya/1/edit I encountered an issue where the button stops working after adding an if condition. I suspect there are some minor bugs in the code, but my level of experience is not enough to pinpoint t ...

When incorporating a CDN in an HTML file, an error message may appear stating that browserRouter is not defined

I am attempting to create a single HTML page with React and React-router-dom. Initially, I used unpkg.com to import the necessary libraries, and I was able to load the page with basic React components. However, when I tried incorporating React-router-dom ...

Is there a way in CSS/3 to dynamically adjust the height based on the width?

Is there a way in CSS/3 to maintain the shape ratio of a div while keeping it responsive? Let's say the container is 100px wide. For example: width: 100%; height: 100%-of-width; Result: The div is 100px wide and 100px high. Another example: ...

Tips for utilizing a variable within a variable containing HTML code

Is it possible to incorporate variables in a JavaScript function that includes HTML code? Let's consider the following example: function SetCFonts() { var Color = $('#CColor').val(); var Font = $('#CFont').val(); var S ...

Is there a way to selectively display a portion of my CSS class based on certain conditions?

Is there a way to conditionally render all of the css inside the following hover psuedoclass based on a variable (data) being not null? Within my React Component that utilizes Material UI makeStyles, I have the following styles: const useStyles = makeStyle ...

Display 1 row of content on larger LG screens and 2 rows on medium-sized MD screens using Bootstrap

How can I achieve 1 row with 12 cells on a large screen in Bootstrap, and for a smaller screen have 2 rows with 6 cells? Here is a visual representation of what I am trying to accomplish: https://i.stack.imgur.com/NgfaP.png This is the code I attempted: ...

Tips for sharing information through a JSON array

"advertisement_types":["ATM","Banner/Poster","Stalls"] Here is the HTML code: input(type='checkbox', value='Mobile/Communication Tower', ng-model='advertisement_types') | Mobile/Communication Tower ...

Animating the size of an element with dynamic content

I am working on a feature where clicking on a card should display a summary. When a new summary is shown, I want the summary container to animate and align its position with the associated card (top). However, despite my efforts, I am facing an issue whe ...

Utilizing AngularJS ng-show to conditionally display content based on data retrieved from an

I am facing an issue with implementing the ngShow directive in my code, where I am trying to display data fetched from an API call. However, despite everything else working correctly, the ngShow directive does not seem to be functioning as expected. Here ...

How can one locate a particular element/style/class in the dev tools DOM while debugging in MUI v5?

Exploring the DOM and pinpointing the specific component file and style block in MUI v4 is a straightforward process: Locating a particular element/style class in MUI v4 However, in MUI v5, this functionality is no longer available, making it challenging ...

Having trouble displaying images in my 360-degree rotation slider

I am completely new to java script, so I have been copying and pasting code. However, it seems like the images are not loading properly. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" ...

Is there a way to determine the length of a variable containing a mixture of characters in HTML and PHP?

Let's say someone wants their username to be GreenApples-72. How can you determine the number of letters, numbers, and symbols in the username and add them together? if((($_POST['username'])<'2')) // Checking if the length of t ...

When I view the website on a tablet in landscape mode, the navigation bar vanishes

I just finished creating a responsive menu for a website. Here's how it works: when viewing the site on a regular browser with a width less than 768px, the navigation menu items are stacked and hidden. To reveal them, the user needs to click on a tog ...

"Stop" and "start" a loop in AngularJS

Feeling a bit lost on how to articulate this inquiry, or even where to start looking for answers. I have a dynamic photo/text feed populating an array, meaning my page is constantly being updated with new information. The influx of data is happening at a ...

The Bootstrap toast fails to appear on the screen

I am currently working on a website project using HTML with bootstrap and javascript. I have been attempting to include a toast feature by implementing the code provided on the bootstrap website: <div class="toast" role="alert" aria-live="assertive" ...

Using two modal popups while passing an identifier

UPDATE: In my investigation, I discovered that a plain input tag without MVC RAZOR works as expected: <input type="text" class="hiddenid2" /> //WORKED However, when using the following code, it does not work: @Html.Editor("id", "", new { htmlAtt ...

Retrieving the value of a radio button using jQuery and Ajax

Looking for assistance with radio buttons... <input type="radio" id="flip" name="flip" value="Head" checked="checked" /> Head <input type="radio" id="flip" name="flip" value="Tail" /> Tail I'm attempting to process a form with ajax, try ...

Trigger AJAX request upon selecting a value from the dropdown menu

I am in the process of creating a basic dropdown menu that is only visible to users on mobile devices when they visit our website. The main objective is to allow users to select a value and then have that value sent via AJAX. For desktop devices, I have s ...