Is there a more efficient method for horizontally and vertically aligning in this particular scenario using HTML and CSS?

Embarking on my HTML/CSS journey, I am taking on the challenge of creating my very first website. Currently tackling the final CSS project for Codecademy.

I've been tinkering with this task for what feels like an eternity and just can't seem to crack it. My goal is to center all the elements within the .mainContainer. It seems logical that the 'Title' should be in the same container as the boxes, but I'm struggling to position it above the boxes while keeping everything centered both horizontally and vertically.

Below is the closest I have come to achieving this. The alignment at the bottom of the boxes looks centered, however, I require all content to be perfectly centered. What puzzles me is why I have used inline-block for .mainContainer, but employed flex for .boxContainer. Removing one property disrupts the centering effect. I never thought multiple display styles could be combined like this...what's the secret behind this?

https://jsfiddle.net/ichristian/ce9mou4w/2/

HTML

<div class='mainContainer'>
  <h2>Title</h2>
  <div class='boxContainer'>
    <div class='box'>
      <p>Box 1</p>
    </div>
    <div class='box'>
      <p>Box 2</p>
    </div>
    <div class='box'>
      <p>Box 3</p>
    </div>
  </div>

</div>

CSS

.mainContainer{
    background-color: orange;
    height: 200px;
    width: 400px;
    align-items: center;
    text-align: center;
    display: inline-block;

}

.boxContainer {
    display: flex;
    align-content: center;
    justify-content: center;
    align-items: center;
}

.box {
  background-color: black;
  color: white;
  height: 40px;
  width: 40px;
}

.box + .box {
  margin-left: 40px;
}

EDIT: Not satisfied with the solution provided by the recommended question. The alternative answer I found below is much more straightforward.

Answer №1

To create the outer container, you can utilize flex-direction with a value of column. For the inner container, set it to row.

.mainContainer {
  display: flex;
  align-items:center;
  justify-content: center;
  flex-direction: column;
  background-color: orange;
  height: 200px;
  width: 400px;
}

h2 {
  margin: 0 0 20px 0;
}

.boxContainer {
  display: inherit;
  flex-direction: row;
}

.box {
  background-color: black;
  color: white;
  height: 40px;
  width: 40px;
  margin: 0 20px;
}
<div class='mainContainer'>
  <h2>Title</h2>
  <div class='boxContainer'>
    <div class='box'>
      <p>Box 1</p>
    </div>
    <div class='box'>
      <p>Box 2</p>
    </div>
    <div class='box'>
      <p>Box 3</p>
    </div>
  </div>

</div>

To adjust the spacing between the title and its sibling container, use a margin property (e.g. apply margin-bottom on the <h2> element).

Answer №2

Follow these instructions:


.mainContainer {
  background-color: orange;
  height: 200px;
  width: 400px;
  align-items: center;
  text-align: center; 
  margin-left:auto;
  margin-right:auto; 

}

Check out this link for more details and some tweaks made to the code: https://jsfiddle.net/aviboy2006/j7za04xu/2/

Increase the width and height of the container:

View the updated version with larger dimensions here: https://jsfiddle.net/aviboy2006/j7za04xu/5/

Perfectly centered both vertically and horizontally:


.mainContainer {
  background-color: orange;
  position: absolute;
    top: 50%;
    left: 50%;
    -moz-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
    padding:10px;
    text-align:center;

}

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

Steps for Removing Multiple CSS Styles from an Element's Style:

When my application generates inline styles, I sometimes need to remove the height, width, and max-width styles from certain elements. I have identified the element using this code: const elems = window.$('.myElements'); window.$.each(elems ...

Effortlessly saving money with just one click

I have a search text box where the search result is displayed in a graph and then saved in a database. However, I am facing an issue where the data is being saved multiple times - first time saves properly, second time saves twice, third time three times, ...

Ways to create a transparent parallax background

Currently, I'm tasked with developing an educational website using HTML and CSS for a school project. Unfortunately, due to restrictions on code.org, I cannot utilize JavaScript files or script tags. Despite successfully implementing a parallax effect ...

Issue with slideout menu hyperlinks malfunctioning

Currently developing a site at , everything seemed ready for deployment until testing in 320x480 mode on mobile revealed that the links on the slideout menu were not working on any mobile device I tried, regardless of resolution or page. I've tried u ...

What is the simplest method for transferring data to and from a JavaScript server?

I am looking for the most efficient way to exchange small amounts of data (specifically just 1 variable) between an HTML client page and a JavaScript server. Can you suggest a script that I can integrate into my client to facilitate sending and receiving d ...

Refining the options in security question dropdown menus

Firstly: The title should mention filtering security options in dropdown lists, but it seems I'm restricted from using the term questions or question in the title. I came across this code example, but it appears to be outdated. Does anyone know why a ...

Design inspired by dot matrix patterns

Is it possible to create a background HTML page filled with a dot matrix designing tool? Can anyone provide guidance on how to achieve this? If I need to use a background-image for this, where can I find the appropriate picture? Thank you to everyone in ...

Ways to achieve perfect alignment for SVG text within its container, as opposed to stretching across the entire webpage

Recently, I've been working on a customizable photo frame designer using SVG. One of the key features allows users to add their own text to the frame. To achieve this, I'm utilizing jQuery's .keyup function. However, the issue I'm facin ...

Is it achievable to modify the appearance of the "Saved Password" style on Firefox?

After creating a login page that initially had a certain aesthetic, I encountered an issue when saving login data in Firefox. The saved login page took on a yellow-ish tint that was not present in my original design: https://i.sstatic.net/LURG3.png I am ...

Tips for creating text that wraps around an image in an editor

On my webpage, I am using an editor called Cleditor jquery plugin. The default setting allows me to insert images, but the text does not wrap around it. I attempted using vertical-align:top, but it did not resolve the issue: What CSS property should I ap ...

Dynamic content moves unpredictably when adding or modifying TextBoxes or DropDownList items

Whenever I navigate from one textBox to another in my .aspx form, it starts jumping around. The problem is exacerbated when I switch focus to or from a DropDownList. I only have a few textboxes on the form and nothing complex like gridviews or labels. So ...

Break the page after generating specific charts with JQuery

I have a task to create multiple charts, where the first page needs to include a header and the first 8 charts. How can I insert a page break after the 8th chart and move on to a second page without a header? Each student has different subjects and score ...

Angular 6: Issue with displaying data on the user interface

Hello! I am attempting to fetch and display a single data entry by ID from an API. Here is the current setup: API GET Method: app.get('/movies/:id', (req, res) => { const id = req.params.id; request('https://api.themoviedb.org/ ...

Implementing HTML tags in C# code

Below is an example of HTML script: <h1> This is heading one </h1> <p> This is paragraph. </p> I would appreciate any recommendations on how to add <html></html> tags to the above script using C#. ...

Error encountered: Unrecognized media in CSS validation and parsing issue

I've been having trouble validating my CSS and keep encountering error messages. Despite ensuring I have closing brackets, there are parse errors on line 39 and unrecognized media issues on lines 79 and 81. Additionally, lines 70 and 89 also trigger p ...

`Enter` within a container

Is there a way to use a controller in order to achieve printing test1 test2 within a <div> element... Currently, the only code I have is a simple Return "test1" & vbNewLine & "test2" However, this code displays the words on a single line ...

Ways to incorporate CSS design into Django input pop-up when the input is invalid

Looking to enhance the error message styling for a Django Form CharField when an incorrect length is entered, using CSS (Bootstrap classes preferred). I have successfully styled the text input itself (check the attrs section in the code), but I am unsure ...

Fill the image with width using Mat

While working on creating cards using Angular Materials, I encountered an issue where the image was not filling up the space as desired. The red area in the image indicates where I want the image to take up space. https://i.sstatic.net/vcc9U.png HTML: & ...

What is the best way to adjust the fontSize of text within a table using Material UI?

In my Material UI table, I am attempting to adjust the fontSize of the contents. However, when I try to modify it using the style={{}} component, the changes are not being applied. <Grid><Typography variant="body1">Fiscal Year </Typography&g ...

Conceal the div class upon clicking it

I'm dealing with a list of videos and I need to hide the class when it's clicked. Check out this sample HTML output: <div id="primary-video"> <iframe id="video" width="100%" height="auto" src="https://www.youtube.com/embed/test" fra ...