将方框放在ul的中心,但将其向左对齐 [英] Place boxes inside ul in center, but align them left

查看:54
本文介绍了将方框放在ul的中心,但将其向左对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到如何将框放在中间,但是将其向左对齐.看来 ul 的宽度不适合内容,因此无法自动而是手动进行设置.但是我不想手动设置它,因为我的内容会动态更改.因此,我需要将框居中,但要使框向左对齐,而无需手动更改和编写脚本.

I can't find how to place boxes in the center but align it to left. It seems that ul has width fit not to content, and it is not possible to set it automatically but manually. But I don't want to set it manually, because my content changes dynamically. So I need boxes to be centered but aligned left with no manual changes and no scripts.

未居中但向左对齐:

Not centered but aligned left:

div {
  padding: 20px;
  width: 200px;
  background-color: green;
  text-align: center;
}

ul {
  list-style:none;
  padding: 0;
  margin: 0;
  text-align: left;
}

ul li {
  width: 40px;
  height: 40px;
  background-color: wheat;
  display: inline-block
}

<html>
<head></head>
<body>
<div>
   <ul>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
 </ul> 
</div>
</body>
</html>

推荐答案

CSS网格可以做到.调整div大小以查看结果:

CSS grid can do it. Resize the div to see the result:

div {
  padding: 20px;
  width: 200px;
  border: 1px solid;
  overflow: hidden;
  resize: horizontal;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
  display: grid;
  grid-template-columns: repeat(auto-fit, 40px); /* width of elements here */
  grid-auto-rows: 40px; /* height here */
  grid-gap: 4px;
  justify-content: center; /* this will do the magic */
}

ul li {
  background-color: wheat;
}

<div>
  <ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
  </ul>
</div>

这篇关于将方框放在ul的中心,但将其向左对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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