How to Center a DIV both Vertically and Horizontally with CSS Positioning?

I'm currently working on a webpage layout where I want to have a main div centered horizontally with three smaller divs inside, aligned both vertically and horizontally with equal spacing. I tried using margin: auto on an empty div to center it in the main div, but I'm having trouble getting the smaller divs to center within that empty div. It seems like the margins are not taking the parent element into account.

I've experimented with various methods to center the elements, but nothing seems to work for me. I would appreciate it if someone could provide guidance on how to achieve this effect using CSS.

Here is a screenshot of the current layout (the red div will be invisible in the final design):

HTML Code:

<html>

<head>
<title>Title Placeholder</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"></link>
</head>

<body>

<div id="title"></div>

<div id="introdiv"></div>

<div id="wrapper">

<div id="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>

</body>


</html>

CSS Code:

html {
background: ##6f7604;
background-image: url("zenbg-1.png"), url("zenbg-2.png");
background-repeat: repeat-x, repeat;
}

#title {
background-color: rgba(83,188,255,0.6);
min-height: 5%;
width: 90%;
margin: auto;
border: 1px solid #ddd;
}

#introdiv {
background-color: rgba(255,207,76,0.9);
min-height: 15%;
width: 70%;
margin: auto;
margin-top: 2.5%;
border: 1px solid #ddd;
}

#wrapper {
background-color: rgba(83,188,255,0.6);
min-height: 65%;
width: 80%;
margin: auto;
margin-top: 2.5%;
border: 1px solid #ddd;
}

#container {
min-height: 10%;
width: 50%;
background-color: red;
margin: auto;
margin-top: 6.5%;
}

.box {
background-color: rgba(255,207,76,0.9);
min-height: 40%;
width: 20%;
margin-left: 5%;
margin-top: 5%;
border: 1px solid #ddd;
display: inline-block;
}

Any help or additional information you may need will be greatly appreciated.

Answer №1

To align an element in the middle and center, you can utilize CSS properties like position: absolute and transform. Here's a simple example:

.container {
  width: 100%;
  height: 300px;
  padding: 20px;
  background-color: #333;
}

.center-container {
  width: 80%;
  height: 250px;
  margin: 0 auto;
  position: relative;
  background-color: #666;
}

center-element {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #999;
  padding: 10px;
}

.item {
  display: inline-block;
  width: 80px;
  height: 80px;
  margin-right: 10px;
  background-color: #ccc;
  float: left;
}
.item:last-child {
  margin-right: 0;
}
<div class="container">
  <div class="center-container">
    <div class="center-element">
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
    </div>
  </div>
</div>

Answer №2

To center elements vertically, apply vertical-align: middle in the following manner

.container {
    background-color: rgba(123,210,45,0.8);
    min-height: 50%;
    width: 25%;
    margin-left: 10%;
    vertical-align: middle;
    border: 2px dashed #555;
    display: inline-block;
}

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

Ways to choose a distant relative in XML using XPath

To target all direct <p>...</p> elements inside a div, the selector would be div/p If I wish to select all second-level nested <p>...</p> tags within a div, I could use div/*/p Can a specific range be specified instead? div/descen ...

Transferring time for streaming MP3 files from server to HTML5 audio

Currently, my node.js server is set up to convert and stream mp3 files in real-time. I have integrated an HTML5 audio tag to play this stream, but I am encountering a problem - the audio element is unable to determine the duration of the mp3 until it has c ...

"Transforming the Website Background with a Splash of Color

I am trying to figure out how to change the color scheme of my website with a button click. Currently, when I select a different color, only the background of the webpage I'm on changes, not the entire website. I have applied CSS but it's not ref ...

Tips for transferring custom data on a form without relying on input fields are an effective way

Is there a way to submit a form with both name and quantity without having an input field for the second variable? I want the quantity get variable to be passed when the form is submitted, but I also need to pass the name quantity that is already displayed ...

What is the best way to set up a server-sent-events broadcast feature in totaljs?

Let's imagine this situation: Client1 and Client2 are currently in session1 Meanwhile, Client3 and Client4 are part of session2 My aim now is to send event "a" to all clients in session1 exclusively. I came across this example: https://github ...

How can I create a one-column layout in CSS grid where one element automatically fills the remaining space after the other elements have taken their own auto widths?

I want a flexible layout with auto width columns for future additions. Avoiding extra wrappers is preferred. CSS grid is the preferred method over flexbox (although flexbox can achieve it with wrappers). This layout is intended for a navigation bar Here&a ...

Refresh PHP Calculator Display Once Results are Shown

Currently working on a basic calculator project coded in HTML, CSS, JS, and PHP. Here is a glimpse of it: The user input retrieval is handled by JS, while the actual calculations and result display are taken care of by PHP. I am striving to clear out the ...

Verify if the value of localStorage matches the specified value, then conceal the element

This is my second query and I'm hoping it covers everything. My knowledge of javascript is limited, which has made it difficult for me to get my code working properly. Despite trying various different approaches, I have been unable to resolve the issu ...

Organizing list items into vertical columns

Could you help me with UL/LI syntax and how to create a wrapping list? For example, I would like to display: 1 2 3 4 5 6 As: 1 4 2 5 3 6 Currently, I have a header, content, and footer all set with specified heights. I want the list to wrap when ...

I am experiencing an issue with the button that is supposed to link to a section within the same page while it is located within the jumbotron. Interestingly, the button

I'm facing an issue with a button placed inside my jumbotron. The button is supposed to link to a specific section within the page, but it's unresponsive. Even hovering over it shows no interaction. Strangely, if I move the button outside of the ...

AngularJS dropdown not reflecting changes when using ng-selected

While working with AngularJS, I have encountered an issue where the first child of the select element remains empty despite my efforts to populate it. Below is the HTML code snippet: <select id="connectTV" aria-label="How many Dish TVs" ng-model="conn ...

Using AngularJS to update attributes in an HTML tag within a string

My string contains HTML tags : var str = "<div><p></p><p><i>blabla</i></p><p><i><b>blaaaaaablaaaaa</b></i></p><iframe src='urlAAA' height='400' width=&ap ...

Guidance on marking a menu item as selected when choosing its sub-item

I've been tasked with creating a menu and I want to ensure that the menu item stays selected when its subchild is selected. Below is a snippet from my CSS file: #wrapper { width:100%; height:500px; } h2 { color:#787878; } // more ...

Switching HTML text by clicking or tapping on it

I'm currently working on a website that will showcase lengthy paragraphs containing complicated internal references to other parts of the text. For instance, an excerpt from the original content may read: "...as discussed in paragraph (a) of section ...

What is the best way to iterate through my array and display each value within my button element?

I have a challenge where I'm trying to iterate over an array named topics. This array contains the names of various people. Within my loop, my goal is to extract each name and insert it into a button as text. When I use console.log within my loop, I ...

Modifying a div element upon the successful completion of an ajax/json request

Currently, I have a form on my webpage for creating a new album. Alongside this form, there is also a delete album form. After successfully creating an album, I want to automatically update the checkbox list in the delete album form with the details of the ...

``Are there any thoughts on how to troubleshoot display problems specifically on mobile

Whenever I use Safari on iOS for my web application, I encounter strange rendering issues. It's odd because the majority of the time everything functions as it should, but every now and then these bugs crop up with no discernible pattern. Examples th ...

Tips for aligning a dropdown button with the other elements in your navbar

I followed the code outline from a tutorial on We3schools, but I'm having an issue with the button not aligning correctly with the navbar. I attempted to adjust the code for proper alignment before publishing, but was unsuccessful. Here is the GitHub ...

Generating PDF files from HTML documents using Angular

I am currently working on an Angular 11 application and I have a specific requirement to download a PDF file from a given HTML content. The challenge is that the HTML content exists independent of my Angular app and looks something like this: < ...

Mastering CSS Sprites: A Guide to Aligning Sprite Buttons at the Bottom

In my web app, I have a bottom navigation bar with 9 buttons, each represented by a Sprite Image having 3 different states. The challenge I'm facing is aligning all the images at the bottom of the nav bar or div. The icons vary slightly in size, and ...