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/
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With