Using `margin: auto;` alone will center a div horizontally, but it won't

My goal is to perfectly center the text within the anchors in my li container, both horizontally and vertically. I've come across a method that involves using text-align: center; on the container for horizontal alignment. However, vertical alignment requires setting the display property of li to table and a to table cell.

Not satisfied with this approach, I decided to place the anchor text inside a div element and attempted to center it using margin: auto;. Strangely, this only worked horizontally despite the fact that the div has a specified height as a block element. Can anyone shed light on why this might be?

html {
  box-sizing: border-box;
}

* {
  box-sizing: inherit;
  margin: 0;
  padding: 0;
}

nav ul {
  display: flex;
  list-style: none;
  justify-content: center;
  align-items: center;
  height: 4em;
  background-color: #783F27;
}
nav ul li a {
    display: block;
    border: solid medium;
    border-radius: 0.4em;
    margin: 0 0.5em;
    width: 7em;
    height: 3em;
    color: goldenrod;
}
a div {
    width: max-content;
    height: max-content;
    margin: auto;
}
<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Learning</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <header>
    <nav>
      <ul>
        <li><a href=""><div>Menu</div></a></li>
        <li><a href=""><div>News</div></a></li>
        <li><a href=""><div>About</div></a>
        <li><a href=""><div>Contact</div></a></li>
      </ul>
    </nav>
  </header>
</body>

</html>

Answer №1

If you want to vertically center your link, consider utilizing flexbox again just like you did with the ul.

To make .nav ul li a display as a flexbox and then vertically align it, use align-items: center;.

Here's the updated code snippet:

html {
  box-sizing: border-box;
}

* {
  box-sizing: inherit;
  margin: 0;
  padding: 0;
}

nav ul {
  display: flex;
  list-style: none;
  justify-content: center;
  align-items: center;
  height: 4em;
  background-color: #783F27;
}
nav ul li a {
    display: flex;
    align-items:center;
    border: solid medium;
    border-radius: 0.4em;
    margin: 0 0.5em;
    width: 7em;
    height: 3em;
    color: goldenrod;
}
a div {
    width: max-content;
    height: max-content;
    margin: auto;
}
<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Learning</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <header>
    <nav>
      <ul>
        <li><a href=""><div>Menu</div></a></li>
        <li><a href=""><div>News</div></a></li>
        <li><a href=""><div>About</div></a>
        <li><a href=""><div>Contact</div></a></li>
      </ul>
    </nav>
  </header>
</body>

</html>

Answer №2

One alternative is to eliminate the fixed height and width of the links and utilize padding as a substitute.

html {
  box-sizing: border-box;
}

* {
  box-sizing: inherit;
  margin: 0;
  padding: 0;
}

nav ul {
  display: flex;
  list-style: none;
  justify-content: center;
  align-items: center;
  height: 4em;
  background-color: #783F27;
}
nav ul li a {
    display: block;
    border: solid medium;
    border-radius: 0.4em;
    margin: 0 0.5em;
    color: goldenrod;
    padding: .75em 2em;
}
a div {
    width: max-content;
    height: max-content;
    margin: auto;
}
<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Learning</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <header>
    <nav>
      <ul>
        <li><a href=""><div>Menu</div></a></li>
        <li><a href=""><div>News</div></a></li>
        <li><a href=""><div>About</div></a>
        <li><a href=""><div>Contact</div></a></li>
      </ul>
    </nav>
  </header>
</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

What is the best way to begin an ordered list from the number 2 instead of 1, while ensuring W3C validity and compatibility with

Is it possible to start an ordered list from 2 instead of 1? I need the solution to be compatible with all browsers, including IE6, and ensure that the HTML and CSS are valid. ...

How to Align React Material UI Grid with Varying Row Counts in Each Column

Objective My goal is to design a component that showcases details about a device, including an icon and its current status. For instance: https://i.sstatic.net/UhpnG.png Approach I've Taken I am attempting to accomplish this by structuring a MUI Gr ...

Transforming the MUI CircularProgress into a half circle shape

After utilizing CirculaProgress, I was able to achieve the following: https://i.sstatic.net/Y0Seo.png Is there a simple method to transform it into a semicircle like shown here? https://i.sstatic.net/D8bKu.png ...

Changing the color variable of an object using an onClick function in JavaScript

I'm currently working on a simple game where users can draw using the keys W, A, S, and D. If you want to take a look at the progress I've made so far, here is a JSFiddle link. There's a collision function in the code that I no longer need, ...

Using HTML5 Canvas: Implementing an Image.onload() function through Image.prototype

I am trying to create a simple function that will refresh the canvas automatically when an image is loaded. The idea is to be able to use code like this: var map = new Image(); map.onloadDraw(); map.src = "images/" + worldmapCanvasShapeImage; Currently, ...

Axis incorporating additional padding for extensive domains

Encountering a peculiar issue with d3 axis generation. When creating a bottom x axis using d3.axisBottom() for ordinal domain values, extra padding is being added at the starting and ending points of ticks on the axis. This happens when the d3.scaleBand() ...

Include dropdown lists for selecting the year, month, and day on a web page

Is there a way to implement a dropdown style date selector that dynamically updates the number of days based on the selected year and month using JavaScript? For example, February 2008 has 29 days, April has 30 days, and June has 31 days. Any suggestions ...

What is the best way to create a blurred effect on an image during loading, and then transition to a sharp image once it is fully loaded?

I'm currently working on a project where I want the images to display as a blurred preview initially, and then become clear once fully loaded. This is similar to the feature seen on Instagram, where the app shows a blurred image before displaying the ...

Using Typescript to mute audio elements within HTML documents

I have a scenario where I want to mute audio that automatically plays when the screen loads. In order to achieve this, I am attempting to add a button that can toggle the audio mute functionality using Typescript within an Angular4 application. The code sn ...

In Javascript, the color can be changed by clicking on an object, and the color

Looking for help with my current HTML code: <li><a href="index.php" id="1" onclick="document.getElementById('1').style.background = '#8B4513';">Weblog</a></li> The color changes while clicking, but when the lin ...

Methods for concealing the "image not found" icon in Internet Explorer and Chrome through CSS

I have images displayed on a webpage. Currently, when an image is not available, both Chrome and IE display a broken image indicator. I want to hide this indicator and only show the alternative text. Is there a CSS solution to achieve this? ...

Node JS login leads to fetching /favicon.ico

I've implemented a login/register system using express (passport) on my website. I'm facing an issue where after the user logs in, they are redirected to /favicon.ico instead of the saved originalUrl. Can anyone help me identify what might be cau ...

Can you explain the significance of the symbol "<<<HTML"?

During my code reading, I came across the symbol <<<H.TML. My colleagues mentioned that it is often used to embed HTML within a PHP file. I attempted to gather more information on its usage but could not find much. Could someone please explain ho ...

Choosing a CSS selector for a class that does not have a specific ID

Looking for a way to select all elements with the class .tab-pane except for those with the id #home. I attempted using .tab-pane:not#home{...}, but it proved unsuccessful. Any ideas on how to achieve this? Sample HTML <div id="home" class="tab-pan ...

Advantages and disadvantages of distinct methods for looping through HTML elements

My JS code generates HTML elements that are structured like this: <div id="container"> <div id="block_1" class="blocks"></div> <div id="block_2" class="blocks"></div> <div id="block_3" class="blocks"></di ...

Using Ajax to submit two forms by clicking a submit button

Explanation : In this particular scenario, I am facing a challenge where I need to trigger another Ajax function upon successful data retrieval, but unfortunately, I am encountering some unknown obstacles. Code: ---HTML Form : <form accept-charset=" ...

The error message states: "change is not defined"

I am encountering an issue where I have 4 input boxes triggering a function on keyup using the onkeyup event. Strangely, I keep receiving an error stating that "change" (the function's name) is not defined. Despite correctly defining the function, I c ...

Unable to fetch css file in Node.js

I am currently in the process of learning Node.js, but I have encountered a small issue with retrieving data from a css file. Interestingly, when I directly add the data to the index file's code, it seems to work perfectly. Let me share the relevant ...

Trouble opening attached html file with Asp.net and Google Charts integration

I am facing an issue with my Asp.Net page that includes a grid and an image. The image is a Google Charts chart with a URL of approximately 1600 characters. To send this content as an email attachment, I created an .htm file containing the grid and the ima ...

The function 'find' cannot be invoked on an undefined object

I'm currently working on implementing objects in my jQuery code. So far, I have the following: var options = { ul: $(this).find('.carousel'), li: options.ul.find('li') } The li property is causing an error - Cannot call meth ...