How can I align two inner boxes vertically in the most efficient manner?

.dd{
  height:100px;
  width:100%;
  border:1px soild red;
  background:#000;
}
.dd .d1{
   height:20px;
   width:20px;
   border:1px solid green;
  display:inline-block;
  
}
.dd .d2{
   height:20px;
   width:20px;
   border:1px solid green;
  display:inline-block;
  
}
.dd .d3{
   height:40px;
   width:30px;
   border:1px solid yellow;
  display:inline-block;
}
<div class="dd">
   <div class="d1"></div>
  <div class="d2"></div>
  <div class="d3"></div>
</div>

Struggling with aligning elements vertically in my project, I'm seeking advice or a better approach. My current method involves setting equal margin-top and margin-bottom when the outer div does not have a set height, achieving a vertical alignment. However, I am open to learning a more effective technique.

Recently, I updated my approach by changing the height value from 50px to 80px in the CSS for innerDivs, only to realize that the adjustment was not effective. My main goal is to center the innerDivs vertically within the fixed-height outer div by making their margin-top and margin-bottom equal. If anyone has a better solution or can provide further explanation, I would greatly appreciate it.

Answer №1

Here's a helpful tip to achieve vertical centering:

.vertical-center {
    display: flex;
    align-items: center;
}

If you also want to horizontally center the items, add the following code:

justify-content: center;

UPDATE Keep in mind that this method will work regardless of the height of the elements inside the flex container.

Answer №2

As per this source, CSS2 allows the use of the table-cell display and the vertical-align property, but personally, I'm not a fan of this coding approach.

Here's a live example of the code in action: https://jsfiddle.net/Laf2wv4n/1/

Answer №3

  • In order to vertically align the inner elements, I utilized the :before pseudo element of the parent (dd).

  • Any inline element can be vertically centered using the vertical-align: middle property.

To achieve this, I employed a pseudo element that functions as an inline-block element with a height of 100% of the parent container.

.dd {
  height: 100px;
  width: 100%;
  border: 1px solid red;
  background: #000;
}
/* added to vertically align the elements inside */
.dd:before {
  content: '';
  height: 100%; 
  display: inline-block; 
  width: 1px; 
  margin-left: -1px; 
  vertical-align: middle; 
}
.dd div {
  vertical-align: middle; 
}
/* end */
.dd .d1 {
  height: 20px;
  width: 20px;
  border: 1px solid green;
  display: inline-block;
}
.dd .d2 {
  height: 20px;
  width: 20px;
  border: 1px solid green;
  display: inline-block;
}
.dd .d3 {
  height: 40px;
  width: 30px;
  border: 1px solid yellow;
  display: inline-block;
}
<div class="dd">
  <div class="d1"></div>
  <div class="d2"></div>
  <div class="d3"></div>
</div>

Answer №4

Aligning text or blocks vertically has been a long-standing issue in HTML/CSS. Over the years, many solutions have emerged, depending on various factors such as browser functionality and the characteristics of the elements involved.

Chris Coyier has compiled these techniques into a comprehensive guide on his website, categorizing them based on their most common use cases.

Check out Chris Coyier's Complete Guide to Centering in CSS

My personal favorite methods are the more modern approaches: utilizing flexbox and aligning elements using the transform: translateY(-50%) rule. These methods are concise and effective.

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

How can I prevent my copy variable from altering the original value variable in Node.js?

Why is it that when I change a variable that is a copy of another variable, both are affected? This concept doesn't seem logical to me. Can you please explain why this happens? It's my first time encountering this behavior in node.js. I am famili ...

I'm encountering the error message "Controller not a function, received undefined" even though I have not declared the controller globally

Encountering the same ERROR Argument 'AveragesCtrl' is not a function, got undefined. Despite attempting various solutions found on SO, I am still unable to resolve this issue. Any insights into what might be causing my error? <div > ...

Is there a way to determine when the callback function has been called for the final time?

Per the documentation on String.prototype.replace(), if a function is passed to String.replace() with a global regular expression, it will be invoked multiple times. Is there a way to pass a callback within this callback to determine when all invocations ...

Kik Card - Using Synchronous XMLHttpRequest within the Kik.js Script

Getting ready to create a mobile web app powered by Kik! First step, insert the Kik.js script at the bottom of your HTML page... <!-- add this script to your webpage --> <script src="http://cdn.kik.com/kik/2.3.6/kik.js"></script> Excel ...

Retrieving a PHP variable from HTML without using a form

Is there a way to pass a variable from HTML to PHP without using a form and the traditional post or get methods? I have tried using the code provided, but I am unable to access the value of the 'buy1' variable in PHP. Is there a way to achieve th ...

Looking for a simple method to display a popover using conditional if/else statements?

On my website, I am utilizing JavaScript to determine the user's Facebook status. This includes checking if the user is already logged in and has allowed our app, if they are logged in but haven't authorized our application, or if they are not lo ...

Determine in JavaScript if one date occurs exactly one week after another date

Currently, I am tackling a date comparison task for our application. The main objective is to compare the Start Date inputted by the user with the Operator/Region Effective Date, which signifies when a new list of product prices becomes valid. Our aim is t ...

What is the best approach to have a method in the parent class identify the type based on a method in the child class using TypeScript?

I'm faced with a code snippet that looks like this. class Base{ private getData(): Data | undefined{ return undefined } public get output(): Data | undefined { return { data: this.getData() } } } class ...

Tips for uploading information to a web service

Issue Description:- I am attempting to access web services from a different domain (i.e. Systems are not locally connected) and encountering the following error: "Failed to load : Response for preflight is invalid (redirect)" var username = "<a href= ...

creating unique styles for your Ionic app with Angular using JSON

Having trouble changing the item color. Does anyone know why my CSS isn't working, or if I'm missing something? <ion-view title="Add order to a table"> <ion-content class="has-header has-subheader"> <ion-list> ...

Connecting Formik with the react-phone-number-input library: A step-by-step guide

I am currently working on developing a form using Formik, Material UI, and the React-phone-number-input library for phone number formatting. I have encountered an issue where the formatted phone number is not being inserted into the Formik state, causing F ...

Challenges encountered when using random values in Tailwind CSS with React

Having trouble creating a react component that changes the width based on a parameter. I can't figure out why it's not working. function Bar() { const p =80 const style = `bg-slate-500 h-8 w-[${p.toFixed(1)}%]` console.log(styl ...

Incorporate a curved progress line into the progress bar

Currently, I am working on creating a customized progress bar: .create-progress-bar { padding: 0 !important; margin: 25px 0; display: flex; } .create-progress-bar li { display: flex; flex-direction: column; list-style-type: none ...

How to make text in HTML and CSS stay at the bottom of a div?

I am in the process of creating a website dedicated to my "Starcraft II" clan. My goal is to have the navigation bar display the text "ALLOYE" and remain fixed at the bottom of the screen. I attempted to achieve this using the following code: vertical-alig ...

An error occurs when calling useSWR in a function that is neither a React function component nor a custom React Hook function

When using useSWR to fetch data from an endpoint, I encountered the following error (I only want to fetch data onclick) "useSWR is called in function `fetchUsers` that is neither a React function component nor a custom React Hook function" Error ...

Determining height of an element in AngularJS directive prior to rendering the view

As I dive into the world of Angular, any assistance is greatly welcomed. My goal is to vertically align a div based on screen size (excluding the header and footer) when the page loads, the window resizes, and during a custom event triggered by the user ex ...

Passing data from client to express.js using Javascript

I'm having trouble sending a variable from a JavaScript application to a Node.js server. Here's the code snippet: //client side $.get('http://smart-shopper.ro/messages?from=lastGeneralTimeStamp', datas => { console.log("dat ...

Center the content within the div

Is there a way to center the content of the second column within this div? I've tried various methods without success so far. I'm currently using Bootstrap 4. Can anyone provide guidance on how to achieve this? <div class="card"> < ...

Using the JSON parameter in C# with MVC 3

I'm facing an issue with sending JSON data from a JavaScript function to a C# method using Ajax. When I receive the data in C#, it's not being recognized as JSON. How can I resolve this issue? If I try to output the received data using Response.W ...

What is the best way to implement spacing between the navigation bar logo, search bar, and links using flex in Bootstrap 5?

I want to customize the layout of my navigation bar using Bootstrap 5. Specifically, I would like the logo text to be on the left, the search bar in the middle, and the user links on the right. How can I achieve this using Bootstrap 5? <!-- NAVIGATION ...