pseudo-element acting like a grid item in CSS grid

不羁的心 提交于 2020-01-09 10:49:13

问题


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/


回答1:


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>


来源:https://stackoverflow.com/questions/45599317/pseudo-element-acting-like-a-grid-item-in-css-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!