Place the vertically centered div with a height that exceeds the viewport's height

I have been trying to find a solution to my question, but I can't seem to locate any answers. I have a webpage with a main div that contains all the content. I centered it using the following CSS:

.center {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

https://i.sstatic.net/bYzy6.png

Everything works well when the height of the div is smaller than the viewport. However, if the div's height exceeds that of the viewport, half of the content ends up off-screen. This issue is particularly visible on mobile devices (see image)

https://i.sstatic.net/NXnw7.png

I thought about applying the transform only on desktop screens, but this would cause problems if the div's height increases. Another idea was to use JavaScript to check if the div's height is less than the viewport's height before applying the transform. However, I would prefer to stick to CSS alone. Any suggestions on how I could solve this?

Answer №1

One way to achieve the desired layout is by using a combination of flexbox and margin tricks:

html,
body {
  height: 100%;
}

body {
  display: flex;
  margin: 0;
}

.center {
  max-width: 50%;
  margin: auto;
}
<div class="center">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas nec mi maximus, pretium nunc eget, congue nulla. Nam ornare ornare nisl accumsan suscipit. Quisque blandit tortor ac placerat lobortis. Orci varius natoque penatibus et magnis dis parturient
  montes, nascetur ridiculus mus. Ut varius a neque a venenatis. Morbi non justo dapibus, bibendum nunc vel, tempus nulla. Nam ornare, sem nec volutpat tincidunt, arcu arcu facilisis nisi, ut lobortis metus ante quis orci. In velit velit, pellentesque
  nec suscipit non, euismod nec metus. Cras pulvinar eu nisl at convallis. Nam vehicula interdum dui, sit amet vestibulum sapien consectetur id. Morbi non velit eros. Fusce ac pretium massa. Nam sit amet nibh ac magna bibendum porta. In maximus tempus
  nulla. Sed a massa ligula. Vestibulum viverra odio quis ex consequat semper. Vestibulum ex lectus, pellentesque sed quam eget, porta volutpat magna. Praesent pulvinar auctor ante, eget dictum tortor egestas non. Donec maximus sem eu nisl commodo, quis
  varius lectus suscipit. In vestibulum est diam, id ornare lacus fermentum a. Fusce dictum ligula eros, non pellentesque lorem pulvinar consectetur. Nunc sapien metus, feugiat ac sagittis sed, euismod sed purus. Curabitur quis iaculis lacus, dapibus
  ultrices leo. Curabitur ac lacinia purus. Pellentesque accumsan pulvinar erat non viverra. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In venenatis porttitor erat non eleifend. In eget auctor nulla.
  Aenean ultricies dapibus nisi eget venenatis.
</div>

Answer №2

My recommendation is to include a margin-top and a margin-bottom in your div element. This adjustment will maintain the appearance on desktop while ensuring the height of your div is appropriate for mobile devices.

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

Tips for creating seamless image transitions using a toggle button

My transition effect is working smoothly, but I am having trouble setting it up for the image. How can I resolve this issue? I attempted the following: var lightsOff = document.querySelector("#lights-off"); var lightsOn = document.querySelector("#lights-o ...

Add small pieces of content to CKEditor

Is there a way to add "atomic" block content into CKEditor? For instance, I would like to add <h1>Test</h1> right after the letter "B" in the sentence <p>A B C</p>. Currently, when using CKEDITOR.currentInstance.insertHtml('&l ...

Retrieve the chosen option from a Select Dropdown and display it in a modal before carrying out the form submission

I need help figuring out how to send a warning message when a "delete" button is clicked on my webpage. I want the message to appear in a modal and display the selected value from a dropdown menu. Here is the code I have so far: <form action="elim ...

Is there a way in JavaScript to prevent the enter key from triggering a mouse click event?

I am facing an issue with my program where I have multiple clickable buttons and the ability to submit by pressing the enter key. However, when I click several buttons with the mouse and then press enter, it not only submits the form but also acts as if ...

Having trouble with your website's container not wrapping properly?

I've run into an issue where my container is not wrapping a border around the other elements, only around the header. I checked with validators for both CSS and HTML but there are no errors being shown. Does anyone have an idea what might be causing t ...

Using JQuery to implement custom validation on a text field is an effective way

How can I validate a text field using Regex and create my own validation rule for starting with "com."? Can you provide me with an example of how to do this? I want the text field to only accept values that start with com. <input id="appPackage" name=" ...

Is there a way to update a PHP include file without needing to refresh the page?

I've been learning as I go, so some of my questions may seem basic or beyond my current knowledge level. However, I find that peer explanations, examples, and advice are the most effective way for me to learn. Thank you in advance for your help. Usin ...

Display the submission timestamp in Angular upon clicking the submit button

How can I capture the date and time when a user clicks the submit button in Angular? For example, if a form with name and email inputs is filled out and submitted, I want to display the date and time along with the name and email in a table. Here is some ...

Angular JS: Grabbing Text from a Specific div and Copying it to Clipboard

I recently developed a Random Password Generator using Angular JS. Here is how the output appears in the application: <div data-ng-model="password" id="password"> <input class="form-control" data-ng-model="password" id="password" placeholder=" ...

Transitioning opacity and visibility in iOS CSS styling

Check out this test on a desktop browser by visiting the following link (JSFiddle): a { background: gray; display: block; margin: 100px; padding: 100px; } a span { opacity: 0; -webkit-transition: 0.5s; visibility: hidden; } a:hover span { ...

Unable to make boxes responsive to size changes in CSS when layered over video background

I am struggling to position my boxes on top of a video background in HTML/CSS. Despite my efforts, the boxes only appear at the bottom and do not move with any CSS adjustments I make. Is there something I am missing or doing wrong in my approach? I want to ...

Is there a way to design a mosaic-style image gallery featuring images of varying sizes in a random and dynamic layout, all without relying

In my quest to create a unique mosaic-style image gallery, I have scoured the internet for suggestions and have come across numerous recommendations for using available plugins. However, I am curious if there is a way for me to personally create a mosaic ...

Tips on ensuring the first column of an HTML table remains fixed in responsive design

I am trying to create a responsive HTML table where the first column remains fixed. I have a select box on my PHP page and I am using AJAX to display data from a database in the HTML table. However, when selecting a value in the select box in a responsiv ...

What is the best way to display a webpage within an iOS app using PhoneGap?

In my iOS phonegap app, I am looking to have a single view that displays a web page. Can someone guide me on how to load this specific view with a particular URL using JavaScript? Although I primarily develop native iOS applications and do not have expert ...

html code abruptly halted due to an unexpected termination of the file

I'm experiencing an issue with my senaraiperalatanstaf.php file. I inserted some PHP code in between, but now I'm getting a parse error indicating an unexpected end of the file. I've tried troubleshooting it without success. Any help would b ...

Receive the innerHTML of an Element after appending additional Elements - Selenium

When working with my table in HTML, I have noticed that the <td> tag can be accessed in two different ways: 1. <td><font size="4" face="Arial"><i>Google</i></font></td> 2. <td>Google</td> I am curr ...

CSS image buttons are causing active_link_to list items to disappear when they become inactive

I'm struggling to get the nth css button/list elements to display correctly using active_link_to. The first css button appears without any problems and is active, but when I try to add new buttons to the list, they seem to disappear. HTML <li cla ...

What is the best way to create a taskbar using HTML or Javascript?

I'm currently developing an innovative online operating system and I am in need of a functional taskbar for user convenience. The ideal taskbar would resemble the Windows taskbar, located at the bottom of the screen with various applications easily ac ...

appear on the screen of a Samsung smart television

Can anyone offer some assistance? I am currently working on this in JavaScript. $('#popup').sfPopup({ text: 'Would You like to close this popup?', buttons: ['Yes', 'No'], defaultFocus: 1, ...

There is an issue with my HTML due to a MIME type error

I am currently facing an issue with my project. I have developed a node js server and now I want to display an HTML file that includes a Vue script loading data using another method written in a separate JS file. However, when I attempt to load the HTML f ...