The alignment of flexbox within a list item is not positioned at the top as expected

When I place a flexbox inside a list item, the content is being pushed down by what seems to be a full line height.

I have tried various CSS properties like setting margin-top: 0 for the flexbox, margin-top: 0 for its children, adding flex-wrap to the flexbox, but nothing seems to work!

.wrapper {
  display: flex;
}
li {
  background: #ccc;
}
<ul>
  <li>
    <div class="wrapper">
      <div>hello</div>
      <div>world</div>
    </div>
  </li>
</ul>

Check it out on CodePen

Answer №1

It appears that the issue is related to the ::marker pseudo-element.

The conflict arises from multiple specifications intersecting, making it unclear what the expected behavior should be.

This situation is complicated because these are still proposals under development and not yet suitable for implementation. A warning in CSS Lists 3 - Positioning Markers highlights this concern:

This section is not ready for implementation. It is an unreviewed rough draft that hasn't even been properly checked for Web-compatibility. Feedback is welcome, but avoid using this part of the spec.

An analysis of how Chrome handles markers internally follows.

To simplify, applying list-style-position: inside to a list item with containing blocks yields:

Illustration:

https://i.sstatic.net/cVE7u.png

Of note is the marker overlapping the div but adjusting its first line box like floats typically do.

A float should not overlap a formatting context root. For instance, display: inline-block establishes a block formatting context.

Example:

https://i.sstatic.net/kt9AY.png

Subsequently, while displaying some float-like characteristics, it operates differently than a traditional float element.

Observations continue regarding various scenarios and how Chrome processes them, including cases involving inline-flex and flex display properties.

Contrasting behaviors of Chrome and Firefox also come into focus when handling markers in different situations.

Answer №2

Solutions

To fix the issue, simply change the .wrapper from display: flex to inline-flex. You can see the updated code in this demo.

Another solution is to set the list-style-type to none. Thanks to @Ricky_Ruiz for this tip. Check it out in this demo.

Browser Behavior

The issue exists in Chrome, Edge, and IE11 while the original code works fine in Firefox and Safari.

Explanation

The cause of the behavior is currently unknown. There seems to be some restriction (possibly due to a marker) preventing access to the top section of the li element by its children.

(UPDATE: A detailed explanation has been provided in another answer.)

During testing...

  • Removing padding and margin from ul and its descendants did not solve the issue.
  • Adjusting line-height and vertical-align also proved unsuccessful.

Setting an equal height on all elements revealed that something is causing the flex container to render lower than expected and overflow its parent.

ul {
  padding: 0;
  margin: 0;
  height: 100px;
  border: 1px solid black;
}
li {
  padding: 0;
  margin: 0;
  background: #ccc;
  height: 100%;
}
.wrapper {
  display: flex;
  padding: 0;
  margin: 0;
  height: 100%;
  border: 1px dashed red;
}
<ul>
  <li>
    <div class="wrapper">
      <div>hello</div>
      <div>world</div>
    </div>
  </li>
</ul>

View revised codepen

Answer №3

To fix this issue, simply include the CSS property display: block in the styling of the li element. By default, browsers will render li elements as list items, so explicitly setting them to display as blocks resolves the problem. The flexbox specifications do not address this directly; they only cover block, inline, and inline-block elements, along with table-cell elements which behave like block-level flex items.

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

A solution for optimizing accessibility by concealing anchor outlines in Internet Explorer and Firefox

Initially, I want to clarify that I acknowledge the fact that removing outlines impairs keyboard navigation. In contrast to Internet Explorer and Firefox, Google Chrome handles this issue by displaying outlines exclusively when the user interacts with the ...

Tips on determining if a string is a properly formatted HTML:

My question is about checking whether selected strings in a web form are valid HTML syntax. How can I achieve this on a button click? function chkhtml() { var code = $("<table><td>"); code.each(function () { if( ...

Achieving a seamless blend of parent background with child background: A step-by

I am trying to make the parent background color overlap the child background color in two divs. Currently, the child's background is overlapping the parent's background. Please refer to the JS-Fiddle link below for more information: <div id=" ...

Building a unique mobile number input box with country code in HTML

Struggling to design a unique mobile input box that separates the mobile number and country code with a divider. Need some assistance in creating this custom input field. Design https://i.sstatic.net/M0Wvs.png Current Implementation <div cla ...

Combine various canvases into a single one (for exporting purposes) with pure Javascript

I'm currently faced with a unique challenge involving the creation of around 200 canvases, each showcasing an image captured from the user's webcam as part of an experimentation process for the "photo finish" technique. My task now is to export ...

What is the best way to allocate a unique color to every item within an array?

I've been working on some JavaScript code that pulls a random color from a selection: const colors = [blue[800], green[500], orange[500], purple[800], red[800]]; const color = colors[Math.floor(Math.random() * colors.length)]; Within my JSX code, I ...

Is there a way to simplify this "stopwatch" even more?

Looking for advice on simplifying my JS stopwatch timer that currently only activates once and keeps running indefinitely. As a newcomer to JS, this is the best solution I could come up with: let time = 0 let activated = 0 function changePic() { if(a ...

Detect keyup event within a dynamically injected iframe

I am currently using a text editor that utilizes wysihtml5. I suspect the text editor is embedded within an iframe. My goal is to capture the key up event inside the text editor and prevent scrolling within it. Below is the code snippet that loads the tex ...

Utilize jQuery to serialize the HTML input elements that are dynamically generated outside of the form

A proof of concept is in progress for an application that involves the generation of HTML elements based on user-configured fields. Here is a sample configuration: // Customer SAM $response = array( array ( NAME => CUSTOMER, TYPE = ...

What are the reasons for avoiding placing CSS code directly within HTML?

Situation: My website is dynamically served, with all CSS and javascript directly embedded into the HTML document to optimize speed. Advantages: Reduces web requests Fewer files downloaded Speeds up webpage loading time Disadvantages: Potential cachin ...

Tips for updating the css class for multiple DOM elements using jQuery

I am currently attempting to modify the class property of a specific DOM element (in this case, a label tag) using jQuery version 1.10.2. Here is the code snippet I have written: var MyNameSpace = MyNameSpace || {}; MyNameSpace.enableDisableLabels = (f ...

By setting up a keydown event listener, I am unable to inspect HTML elements by using the F-12 key shortcut in Chrome

Recently, I encountered an issue where adding a keydown event listener in my JavaScript code prevented F-12 from working properly. window.addEventListener("keydown", function (event) { if (event.defaultPrevented){ retu ...

Can the PHP stylesheet import be configured to exclude a specific string?

Can I import a PHP stylesheet named style.php into my HTML document? Is there a way to delete certain strings from style.php, such as <style> tags, before importing it using traditional methods like <link>? ...

Resizing an image based on the coordinates of a click position by utilizing jQuery

I'm new to experimenting with code, and I've been playing around with trying to shrink an image to nothing at a central point. I've found some success using a mix of the code snippet below and relative positioning in my CSS. $(function() ...

Utilizing Isotope JS on your Wordpress website

I'm in the process of integrating the .js plugin, Isotope, into my Wordpress installation. It should be positioned at the bottom of this page: To achieve this, I am referring to an example on codepen: https://codepen.io/desandro/pen/mEinp The script ...

What is the best way to conceal the jqgrid entirely while it is still loading?

Having an issue with my jqgrid. As I load the table and fetch a large amount of data from the database, the loading process naturally takes a few seconds. However, during this time, I can see the column headers without any rows or styles applied to the jqg ...

The PHP language includes a print language construct for outputting text

Having some trouble with a PHP script in my assignment related to page handling. When I submit it through another PHP page, it is showing the actual PHP code instead of executing properly, but it works fine when run standalone. I've created an HTML l ...

Aligning SVG clipping path using CSS

This problem has me stumped! I need to center the SVG clip within the surrounding div, just like in this example: http://jsfiddle.net/ztfdv9qh/ - Make sure to check the link because the SVG is quite long! <div class="svg-wrapper"> <div class ...

Using Column CSS Property with Google Maps in Chrome: A Potential Bug?

I'm facing an interesting issue and I could use some help understanding or fixing it. It seems like there might be a bug or a solution to this problem. I am currently working on a layout using the CSS3 property columns. Everything looks fine in Firefo ...

I am having trouble with node.js express not recognizing the path to my CSS files

My objective is to load information onto an HTML page using Node.js and Express. The issue I am facing is that when I try to open the main page (which displays all the books from the database), everything works smoothly - the CSS and JS files are located ...