Center the two consecutive <div> elements within the container

There is a situation where

<div id="container">
     <div id="div2">Title</div>                
     <div id="div3">text text</div>
</div>

and in this scenario,

#container {
    height:500px;
    width:100%;
    text-align: center;
}

#div2, #div3 {
   width: 50%;
}

Is there a method to align both #div2 and div3 precisely at the center of the #container, both horizontally and vertically, while allowing their height to adjust dynamically?

Answer №1

It's quite a challenge to determine the best solution for your specific width without knowing the contents of your inner divs. However, I have some suggestions that may be helpful to you.

Please note: The JsFiddle examples provided below have been modified to include color for better visualization of the positioning effects.

Option One: The Floater

This option involves adding three elements - display, vertical-align, and float to your CSS. This results in the following code:

#container {
    height:500px;
    width:100%;
    text-align: center;
    background-color:blue;
    display: table-cell;
    vertical-align:middle;
}

#div2, #div3 {
    float:left;
    text-align:center;
    width: 50%;
    background-color:orange;

}

I will elaborate on why these methods were chosen shortly.

Option Two: Boxception

This option includes margin, display, and vertical-align properties in your CSS:

#container {
    height:500px;
    width:100%;
    text-align: center;
    background-color:blue;
    display: table-cell;
    vertical-align:middle;
}

#div2, #div3 {
    margin: 0 auto;
    text-align:center;
    width: 50%;
    background-color:orange;

}

The use of table-cell display along with vertical-align can help position items within the outer div in the center.

The main difference between the first and second options is that the float property may not perfectly center the content vertically, unlike using margin which ensures horizontal centering.

Remember, the width of the div will expand based on its content (meaning it will only appear as a small line if there's no content). Check out this example for clarification.

Answer №2

apply the CSS properties float: left; and height: 100%;

JSFIDDLE

Answer №3

You can achieve this layout using flexbox in your existing HTML structure.

FIDDLE (Includes vendor prefixes for older browsers)

CSS

#container {
    height:800px;
    text-align: center;
    background: lightblue;
    display: flex;
    align-items: center; /* center horizontally */
    flex-direction: column;
    justify-content: center; /* center vertically */
}

#div2, #div3 {
   width: 50%;
    background: teal;
}

To simplify the process, consider wrapping div2 and div3 elements within a parent div to easily align them together.

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

Struggling to make JavaScript read JSON data from an HTML file

I am currently working on developing a word search game using django. One of the tasks I need to accomplish is checking whether the entered word exists in a dictionary. To achieve this, I have been converting a python dictionary into JSON format with json. ...

Activate the datepicker in Angular by clicking on the input field

This is my html file: <mat-form-field> <input matInput [matDatepicker]="picker" placeholder="Choose a date"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-date ...

Guide to integrating PHP and MySQL with HTML

I am venturing into the world of php for the first time in order to establish a connection with MySQL on my raspberry pi. Both the server and MySQL are up and running on the Pi, and I am seeking to modify my index.html file to display a value stored in the ...

Setting the border of a different element when focus is on an input control: tips and tricks

I've created a form with different input controls structured like this: <div class="form-group mb-3"> <div class="input-group"> <input asp-for="Email" class="form-control" ...

Is it advisable to incorporate the <main> element in my code?

While browsing through w3schools, I came across the <main> element. However, according to caniuse.com, this element is not supported by IE, Opera Mini, and the UC Browser for Android. Should I opt for using a <main> element instead or stick wi ...

Optimizing VueJS applications with browser caching features for faster loading

I've encountered an issue with my VueJS app. After running npm run build, a new set of dist/* files are generated. However, when I upload them to the server (replacing the old build) and try to access the page in the browser, it seems to be loading th ...

I am perplexed by JQuery. It is returning true when comparing an input value from a number type input, and I cannot figure out the reason behind it

Seeking guidance on a perplexing issue. Here is a basic code snippet to depict my dilemma: html: <form> <input type="number" id="someNumber"> <input type="button" id="submitBtn"> </form> jquery: $("#submitBtn"). ...

Cross-browser compatibility issue: Chrome displays image class in HTML CSS, while Firefox does not

I am building a webpage and have encountered an issue with displaying images in different browsers. Specifically, the image appears correctly in Chrome and Safari but doesn't show up in Firefox. By "doesn't show," I mean that the image is not vi ...

I Tried Adding Up All the Numbers, but It Doesn't Seem to Work for Every Dynamic Total Field

In my project, I am utilizing Laravel 5.7 and VueJs 2.5.*. The issue I am facing is that when I input values, the Total field calculates correctly. However, when I dynamically add rows for items, the calculation only works for the first row and not for the ...

Assign separate classes to even and odd div elements

My PHP code block has this structure: $flag = false; if (empty($links)) { echo '<h1>You have no uploaded images</h1><br />'; } foreach ($links as $link) { $extension = substr($link, -3); $image_name = ($extensi ...

Do HTML attributes that are customized without the data-* prefix considered valid?

When it comes to AngularJS, the data- prefix is an option but not a requirement in their examples. Should I decide to include the data- prefix in my project, and what are the benefits of doing so? Will my HTML still be valid even if I choose not to make u ...

Problem with HTML relative paths when linking script sources

Having trouble with a website I constructed using Angular. The problem lies in the references to javascript files in index.html. The issue is that the paths in the HTML are relative to the file, but the browser is searching for the files in the root direct ...

Initial loading issue with HTML5 Canvas in Android WebView

As I work on developing a HTML5 canvas-based game within a WebView of an existing application, I encounter a puzzling issue. Upon the initial run of the game, everything seems to be in order - logs indicate that it's ready and running, yet nothing is ...

React JS issue with SVG linearGradient not displaying accurate values

Within my component, I am working with SVG paths and a linearGradient value passed down from the parent component through static data. The properties 'startColor' and 'stopColor' are used to define the gradient colors for each element. ...

What is the best way to combine a top <div> with a bottom <div> in an image without creating unsightly white gaps?

I need help overlapping two divs on top of an image in HTML. The first div should cover part of the top area of the image, while the second div should cover part of the bottom area of the image. These divs should be displayed over the image without leaving ...

Tips for modifying the text color of radio button choices in HTML and CSS

I have set a black background image for my HTML page. How can I change the radio button labels/texts to white, similar to the questions? This is the code snippet that shows how it currently looks on the page: View Image <hr&g ...

Identifying and handling overlay blockers using Selenium technology

Currently, I am conducting tests on a website that utilizes in-browser pop-ups to display details about objects. These pop-ups are occasionally modal, meaning they render the rest of the screen unusable and activate a gray transparent overlay that covers e ...

Prevent a function from executing using ClearTimeout()

Looking for a way to control the progress of my progress bar using two buttons. Here's the code snippet: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0 /jquery.min.js"></scr ...

Change the marquee scrolling back to its original starting point

I am trying to implement a continuous image scroll (marquee) in HTML. My goal is to have the marquee stop scrolling when the mouse hovers over it, with the images returning to their initial position. Once the mouse moves away, I want the marquee to resume ...

Ensuring WCAG Accessibility Compliance - mandate the inclusion of at least one input in a fieldset

I'm working on a form where users need to provide at least one contact method from a group of fields, such as home, work, or mobile phone number. How can I ensure this meets the latest WCAG 2.2 standards? <!-- Other fields above and below --> ...