CSS网格中的浮动元素

问题描述 投票:5回答:3

我正在编写我的第一页,我想使用CSS网格display: grid

它工作得很好,但我遇到一个小问题,我想要float经典的元素 - 文本浮动图像,报价等。

我只是给了一个元素一个float: left,令我惊讶的是,float完全被忽略了。该元素仍然是一个完整的“网格行项目”。

短代码示例:

main {
  display: grid;
  grid-template-columns: 5% 5% 1fr 5% 5%;
}

main > * {
  grid-column: 3;
}

blockquote {
  grid-column: 2 / -2;
}

blockquote.float-left {
  grid-column: 3;
  float: left;
}

更大的例子,我创造了一个Codepen

不幸的是,我还没有发现任何相关信息,所以我的问题是:有没有人为此解决问题?我忽略了什么吗?或许那可能还不可能?

先感谢您! :)

Codepen - 链接:

https://codepen.io/anon/pen/GQWPWX

css css3 css-float css-grid
3个回答
4
投票

您不能浮动网格项。这样做会完全干扰网格布局。

如果要浮动元素,请从网格布局中删除它们,将display: grid指定给其他中间元素,或者不使用网格布局。


2
投票

浮动在网格容器上受到尊重,但在网格项上完全忽略它们。

此行为在本节的CSS Grid规范中定义:

这里已经讨论过这个问题,但还没有解决方案:


1
投票

有可能获得你想要的效果,但它确实涉及一些额外的标记。由于网格仅影响直接子元素,因此您可以将要浮动的内容(图像,块引用等)和要围绕它的文本放入嵌套在容器内的单独div中,其中应用了display:grid。

例如:

<div class="playerinfo">
<div class="content">
<img class="floatleft" src="images/kane-williamson-sml.jpg" alt="Kane Williamson">
<p> Kane Stuart Williamson (born 8 August 1990) is a professional cricketer from New Zealand who currently plays as a batsman for Northern Districts in New Zealand domestic cricket, the Sunrisers Hyderabad in theIPL, and New Zealand internationally. He made his first-class debut in December 2007 and his IPL debut in 2015.[1] He made his U-19 debut against the touring Indian U-19 team in 2007 and was named captain of the New Zealand U-19 team for the 2008 U-19 Cricket World Cup. Williamson also represented New Zealand at the ICC Cricket World Cup 2011 hosted by Subcontinental nations and the ICC Cricket World Cup 2015 hosted by New Zealand and Australia. On 14 August 2013, Williamson signed for Yorkshire for the rest of the English county season. On February 16 2015, Sunrisers Hyderabad signed Williamson in the IPL for US$96,500.
            </p>
            </div>
        </div>

使用这个CSS效果很好。

.playerinfo{
        display: grid;
    }

    .floatleft {
        float: left;
        padding-right: 5px;
        padding-bottom: 1px;
    }
© www.soinside.com 2019 - 2024. All rights reserved.