11

I'm creating a form that has required fields. To mark these as required, I'm putting an asterisk (*) as a ::before element and floating it right so it is by the top right hand corner of the field.

The issue I'm having is a few of these fields are positioned with CSS Grids and when I add a ::before element to the grid, it is treated as another grid item and pushes everything over to a new grid row.

Why is CSS grids treating the ::before element as another grid item? How would I make the asterisk be positioned like the input elements?

Here's the basic HTML/CSS:

html {
  width: 75%;
}

ul {
  list-style: none;
}

input {
  width: 100%
}

.grid {
  display: grid;
  grid-template-columns: .33fr .33fr .33fr;
}

li.required::before {
  content: '*';
  float: right;
  font-size: 15px;
}
<ul>
  <li class="required">
    <input type="text">
  </li>
  <li class="grid required">
    <p>one</p>
    <p>two</p>
    <p>three</p>
  </li>
  <li class="required">
    <input type="text">
  </li>
</ul>

Here's a fiddle: https://jsfiddle.net/zbqucvt9/

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Andrea
  • 918
  • 2
  • 9
  • 13
  • 3
    A pseudo-element generates the same kind of box that an actual element does. As far as CSS layout is concerned, a pseudo-element box and an actual element box are two of a kind. You'll find pseudo-element boxes behaving identically to actual element boxes in pretty much any other situation. – BoltClock Aug 10 '17 at 06:15

1 Answers1

10

Pseudo-elements are considered child elements in a grid container (just like in a flex container). Therefore, they take on the characteristics of grid items.

You can always remove grid items from the document flow with absolute positioning. Then use CSS offset properties (left, right, top, bottom) to move them around.

Here's a basic example:

html {
  width: 75%;
}

ul {
  list-style: none;
}

input {
  width: 100%
}

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

li {
  position: relative;
}

li.required::after {
  content: '*';
  font-size: 15px;
  color: red;
  position: absolute;
  right: -15px;
  top: -15px;
}
<ul>
  <li class="required">
    <input type="text">
  </li>
  <li class="grid required">
    <p>one</p>
    <p>two</p>
    <p>three</p>
  </li>
  <li class="required">
    <input type="text">
  </li>
</ul>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701