Unable to properly vertically center multiple divs within a parent div and align their elements vertically within them

I'm diving into the world of HTML/CSS and grappling with various concepts. My goal is to vertically align 2 divs within a larger div, as well as center the contents within those divs.

HTML:

<html>
<head>
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
    <div id="MainDiv">

      <div id="SubDiv">
        <form method="POST">
            <input type="text" name="example1" class="Text">
            <input type="text" name="example2" class="Text">
            <input type="submit" value="Go"> <br>
        </form> <br/>
      </div>

      <div id="SubDiv">
          <input type="button" value="Button 1"/>
          <input type="button" value="Button 2"/>
      </div>

  </div>
</body>

CSS:

#MainDiv 
{
    width: 60%;
    height: 30%;
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
    text-align: center;
    border:  1px solid black;
}

#SubDiv
{
    width: 90%;
    height: 45;
    margin: auto;
    border:  1px solid black;

}

.Text
{
    width: 40%;
}

Check out the result here: the main div centered perfectly, but I'm struggling with vertical alignment of other elements.

Despite my efforts to find solutions, nothing seems to work or only complicates things further. Any guidance would be greatly appreciated.

Answer №1

If you're looking to achieve vertical centering, flexbox is a great option to consider.

Check out this helpful introduction to flexbox:

Answer №2

Centering content vertically can be a bit more challenging than centering horizontally.

To achieve this, create a container for your Subdiv elements and give it an id of SubDivContainer. Then apply styles to the container to center its content vertically.

#SubDivContainer {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
}

Combining everything together:

#MainDiv 
{
  width: 60%;
  height: 120px;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
  text-align: center;
  border:  1px solid black;
}

#SubDivContainer {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
}

#SubDiv
{
  width: 90%;
  height: 45;
  margin: auto;
  border:  1px solid black;
  
}

.Text
{
  width: 40%;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<div id="MainDiv">
          <div id="SubDivContainer">
            <div id="SubDiv">
              <form method="POST">
                  <input type="text" name="example1" class="Text">
                  <input type="text" name="example2" class="Text">
                  <input type="submit" value="Go"> <br>
              </form> <br/>
            </div>

            <div id="SubDiv">
                <input type="button" value="Button 1"/>
                <input type="button" value="Button 2"/>
            </div>
          </div>
      </div>
</body>
</html>

Answer №3

Here is a method to achieve this: I have enclosed two inner divs within a single container div and centered it. All elements inside the inner divs are aligned using the line-height property set to the height of the div, and I have removed the BR elements.

body, html{height: 100%}
.mainDiv 
{
    width: 60%;
    height: 30%;
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
    text-align: center;
    border: 1px solid black;
}
.mainDiv>div{
    height: 90px;
    width: 90%;
    margin: auto;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}
.mainDiv>div>div{
    width: 100%;
    height: 50%;
    border: 1px solid black;
    line-height: 45px;
}

.mainDiv input[type=text]{
    width: 40%;
}
<html>
  <body>
    <div id="MainDiv" class="mainDiv">
      <div>
        <div>
          <form method="POST">
            <input type="text" name="example1">
            <input type="text" name="example2">
            <input type="submit" value="Go">
          </form>
        </div>

        <div>
          <input type="button" value="Button 1"/>
          <input type="button" value="Button 2"/>
        </div>
      </div>
    </div>
  </body>
</html>

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

Use column formatting for the table's body section

I have written the code below in HTML to create a table. I am looking to apply a specific style to the table body elements in a column that has been assigned a CSS class, while excluding the header columns from this style application. As an example, I hav ...

Comparing React's Styled-components, JSS, and Emotion: Which is

As a CTO, I am faced with the decision of choosing between three popular CSS-in-JS libraries: jss emotion styled-component. I will keep this question focused and avoid straying into subjective territory. If necessary, I will answer it myself by asking sp ...

What is the best way to specify the CSS :hover state within a jQuery selector?

I am trying to change the background color of a div element when hovered using jQuery, but for some reason the following code is not working as expected: $(".myclass:hover div").css("background-color","red"); Can someone provide guidance on how to achiev ...

Unlock the power of VueJS with advanced checkbox toggling for array data

I have encountered an issue while working with VueJS regarding the implementation of two features for a set of checkboxes. Initially, the checkboxes are generated dynamically. I am in need of a master 'toggle' checkbox that can toggle the stat ...

Is it possible to simultaneously employ two asynchronous functions while handling two separate .json files?

Is it possible to work with 2 .json files simultaneously? My attempt did not succeed, so I am looking for an alternative method. If you have a suggestion or know the correct syntax to make this work, please share. And most importantly, does the second .j ...

Creating a stylish button using a combination of CSS and Javascript classes within a webpage layout

Is it feasible to include a button in the layout that has HTML, CSS styles, and JavaScript functionality? For instance: This button is designed with both CSS styling and JavaScript classes. How can one incorporate CSS and JavaScript along with HTML conte ...

Unable to apply the CSS styles on the webpage

I'm having trouble adjusting the CSS for a specific div with the class .cropper inside a component named image-cropper, and I can't figure out why it's not taking effect. Here is an image of the particular div. Below is the CSS code I atte ...

What steps are necessary to add a Contact Us form to my HTML website?

Currently, I am searching for a way to add a "Contact Us" section to my website that is completely HTML-based. I believe the best approach would involve using a PHP script to handle sending emails from a form on the Contact Us page, but I am not familiar ...

Ensuring scroll position remains fixed post screen rotation in HTML/Javascript

Is there a foolproof method to retain the scroll position in an HTML document following a screen rotation? While this issue is specifically in a Cocoa Touch UIWebView, it seems to be prevalent across different platforms. The standard practice appears to re ...

Incorporating Javascript jQuery functionalities from an external file

I have encountered an issue when trying to run my index.html file with the control.js file that I outsourced. It seems like they are not working together properly: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.c ...

Creative Solution for Nested Forms

I am currently facing a challenge with nested forms in my PHP project. I need to include a form for AJAX image upload within another form so that I can pass the file path to the main form. The example code snippet is provided below; <form> <f ...

Column Flow in CSS Grid: Maximizing Auto-Fit - How to Optimize Row Layouts?

Having some trouble understanding how auto-fill and fit work in grid layouts. I am familiar with basic CSS, but new to working with grid layouts. I have a set of checkbox items with labels that I want to display in columns depending on screen size, with c ...

Having trouble aligning the form in the center?

Despite #container being centered, I am struggling to center the <form>. It is important for me to have all elements inside the form aligned horizontally and despite trying various techniques, it is not working as expected. <!-- Container Start - ...

Is there a way to dynamically update the text in an HTML element with a randomly generated value using JavaScript?

Currently, I am working on a coding project where I am attempting to create a flip box that reveals the name of a superhero from an array when clicked by a user. The code pen link provided showcases my progress so far: https://codepen.io/zakero/pen/YmGmwK. ...

Saving an image and form data together in local storage can be accomplished by using JavaScript

Is there a way to save an image to local storage along with form data? I would like to store the form data in a database and keep the image in local storage. Any help would be greatly appreciated. Thank you! <form id="saveImageForm"><input type ...

Disabling a jQuery function on an external page: Step-by-step guide

I have encountered a challenge while trying to load an anchor tag on an external page using a specific method: <a href="page.html#div> This method is meant to link me to another page's particular div. <div name="div"> stuff </> H ...

Ways to repair an element

Can anyone help me troubleshoot the issue with my count text on a div block? It seems to be affected by changes in screen size. Normal https://i.stack.imgur.com/RZkgr.png On screen resize https://i.stack.imgur.com/hTdCG.png The Code: span.right-cor ...

What advantages does incorporating inline CSS offer in comparison to using an external CSS file for background images?

I'm currently debating the best approach to take in this situation. Let's say I have a background image that I want to use on multiple pages, each with a different background image. The pages themselves must be responsive. Would it be better to g ...

"JQuery event handlers not functioning as expected: .click and .on failing

For some time now, I've been facing this issue and I'm at a loss trying to figure it out. I have attempted various solutions such as using .click(), .on(), .delegate, and even utilizing .find() to locate the specific element causing the problem. ...

Troubles with z-index: issues arise when combining relative and absolute positioned divs

Struggling with my z-index arrangement here. In a nutshell, I have an absolute div positioned beneath a relative div called container. Inside the container, there are three divs: left, center, and right, all with absolute positioning. I am trying to get ...