伪元素在CSS网格中扮演着一个网格项目的角色 [英] pseudo-element acting like a grid item in CSS grid

查看:127
本文介绍了伪元素在CSS网格中扮演着一个网格项目的角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个需要字段的表单。为了将这些标记为必填项,我将星号(*)作为 :: before 元素并将其右移,使其位于字段的右上角。

我遇到的问题是这些字段中的一些使用CSS网格定位,并且当我添加 :: before 元素添加到网格,它将被视为另一个网格项,并将所有内容都推送到新的网格行。



为什么CSS网格将 :: before 元素作为另一个网格项?我如何让星号的位置像输入元素一样?



以下是基本的HTML / CSS:

 

< ul> < li class =required> < input type =text> < /锂> < li class =grid required> < p为H.一个< / p为H. < p为H. 2< / p为H. < p为H. 3< / p为H. < /锂> < li class =required> < input type =text> < / li>

https://jsfiddle.net/zbqucvt9/

就像在flex中一样容器)。因此,它们具有网格项目的特征。

您可以始终使用绝对定位从文档流中移除网格项目。然后使用CSS偏移属性( left right top bottom )来移动它们。



这里有一个基本的例子:

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;红色;位置:绝对;正确:-15px; < ul>

 

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>

这篇关于伪元素在CSS网格中扮演着一个网格项目的角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆