如何使CSS网格位于页面中心

时间:2019-05-31 19:18:20

标签: css

我试图将网格移动到页面中心,我不知道为什么它不起作用

我看了很多例子,我看到有人在用这个: justify-content: center;
即使我尝试了它也行不通。

这是我的代码

ul {
  list-style-type: none;
  background-color: silver;
  padding: 10px;
  text-align: center;
  margin: none;
}

p {
  text-align: center;
  padding: none;
}

li {
  display: inline;
  padding: 10px;
}

a {
  color: yellow;
}

.testing {
  padding: 150px;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-gap: 10px;
  /* next comment was fixed to meet syntax in a plain style sheet */
  justify-content: center;
  /* its not moving to the center of the page*/
}

.testing div {
  width: 225px;
  height: 225px;
  background-color: blue;
}
<ul>

  <li><a href=" ">Home</a ></li>
  	<li><a href="#news">News</a ></li>
 	 <li><a href="#contact">Contact</a ></li>
  
</ul>

     <p>hellow world</p >

 <div class = "testing">
<div></div>

2 个答案:

答案 0 :(得分:1)

网格居中,您只给它3个相等的列,但只有一个子元素,因此div显示在网格的最左列。如果将CSS更改为grid-template-columns: 1fr或在中心定义了template area,它将按预期显示,但是只有一列会引起您为什么要使用网格布局的问题。您要构建哪种布局?也许flexbox解决方案可以更好地满足您的需求?

答案 1 :(得分:1)

只需在padding: 150px;(“测试”类)上将padding: 50%;更改为.testing

这应该有效。


最诚挚的问候

布拉卡(Brhaka)