繁体   English   中英

在CSS网格中居中图像

[英]Centering an image in CSS grid

我正在尝试修复网格布局。

首先,图像应位于.container的中心。 我试过使用align-self: center; ,但这没有用。

标题和段落确实搞砸了。 在此之前,该段落一直压低图像,因此我想如果我给它们(和标题)两个自定义grid-row值,它们将是固定的,但相反,我将所有这些元素彼此重叠。 我需要正确订购它们。 H3下的段落和H1下的H3。

 .container { display: grid; grid-template-columns: auto auto auto; grid-template-rows: 100%; } .container img { grid-column: 1 / 2; grid-row: 1; } .container h1, h3 { grid-column: 3; grid-row: 1; line-height: 0.35; } .container p { grid-column: 3; grid-row: 1; width: 350px; } 
 <div class="container"> <h1>-[IFwsI]- Jail</h1> <h3>More than 40 000 registered players</h3> <p>The most active, and one of the most successful servers. Jail has a set of rules players need to follow and enjoy the roleplay of inmates vs. CTs scenario</p> <img src="https://i.imgur.com/epqMIJv.jpg" height="418" width="740" /> </div> 

为文本和图像创建列,以使其更易于管理。

看一下您可以以多种方式控制每一列的宽度的grid-template-columns 我刚刚将它们的宽度设置为33%

https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns

justify-content: center将列放在水平居中位置。

align-items: center将项目垂直对齐。

为了更改顺序,我创建了一个新的类.column--left带有grid-row: 1将其移到第一列。

 .container { display: grid; grid-template-columns: 33% 33%; justify-content: center; align-items: center; grid-gap: 10px; height: 100vh; } .column.column--left { grid-row: 1; } img { max-width: 100%; height: auto; } 
 <div class="container"> <div class="column"> <h1>-[IFwsI]- Jail</h1> <h3>More than 40 000 registered players</h3> <p>The most active, and one of the most successful servers. Jail has a set of rules players need to follow and enjoy the roleplay of inmates vs. CTs scenario</p> </div> <div class="column column--left"> <img src="https://i.imgur.com/epqMIJv.jpg" height="418" width="740" /> </div> </div> 

...但是相反,我让所有这些元素相互重叠。

在您的代码中,您明确地告诉它们彼此重叠。

.container h1, h3 {
  grid-column: 3;
  grid-row: 1;
  line-height: 0.35;
}

.container p {
  grid-column: 3;
  grid-row: 1;
  width: 350px;
}

h1h3p都放在p 3列第1行中。为什么它们不重叠?

这是另一种可能对您有用的方法:

 .container { display: grid; height: 100vh; align-items: center; grid-column-gap: 20px; grid-template-columns: 1fr 2fr 2fr 1fr; grid-template-areas: " . pic header1 . " " . pic header3 . " " . pic ptext . " " . pic ptext . " } .container > h1 { grid-area: header1; } .container > h3 { grid-area: header3; } .container > p { grid-area: ptext; } .container > div { grid-area: pic; } .container img { width: 100%; object-fit: contain; } * { margin: 0; } 
 <div class="container"> <h1>-[IFwsI]- Jail</h1> <h3>More than 40 000 registered players</h3> <p>The most active, and one of the most successful servers. Jail has a set of rules players need to follow and enjoy the roleplay of inmates vs. CTs scenario</p> <div> <img src="https://i.imgur.com/epqMIJv.jpg" height="418" width="740" /> </div> </div> 

jsFiddle演示

这是使用Firefox的网格覆盖工具的代码可视化。

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM