html中div标签居中为什么调节不了?

div标签已经用margin:0,auto;还是不能居中块元素。

margin:0 auto;需要搭配width或者max-width使用,就是块级元素需要有宽度并且小于父容器宽度,才会在父容器中居中。如果不设置由于是块级元素是自动填充满整个父容器的,所以看起来没居中一样。


<style>
.centerblock{margin:0 auto;width:680px;background:#ccc;}
</style>
<div class="centerblock">centerblock<br>centerblock</div>

中间不需要逗号,还要那个逗号是中文的吧!

试试在style的相关class加上这段
display:flex;//flex布局
justify-content:center;//设置弹性盒子元素在主轴的对齐方式,这里direction是column只设置垂直居中
align-items:center;//子元素水平居中显示
flex-direction: column;//垂直还是水平排列

<style>
  div{
    margin:0px auto;
    width:300px;
    background-color: blue;
  }
</style>

这样写,中间没有逗号的,它的意思据上边距0px; 左、右、下自适应。