简体   繁体   English

div的水平居中可以通过左右边距自动,宽度或最大宽度(而不是最小宽度)来完成?

[英]Horizontal centering of a div can be done by margin-left and right auto, together with a width, or max-width, but not min-width?

In the old days before having max-width and min-width , we have to set the width to some value other than auto , together with margin-left and margin-right to auto , for the div to be horizontally centered. 在具有max-widthmin-width过去,我们必须将width设置为auto以外的其他值,并将margin-leftmargin-rightauto ,以使div水平居中。

Now that we have max-width and min-width , we can also set the max-width to some value other than none to horizontally centered it? 现在我们有了max-widthmin-width ,我们还可以将max-width设置为某个值,而none将其水平居中吗? Is there any spec for it? 有什么规格吗?

PS min-width won't work as the div will span the whole width, so you can consider it horizontally centered, except that the left and right margin are both 0 , so there is no horizontally centering effect. PS min-width将不起作用,因为div将跨越整个宽度,因此您可以将其视为水平居中,除了左右边界均为0 ,因此没有水平居中效果。

Example: 例:

width : https://jsfiddle.net/dtr7t4z7/1/ widthhttps : //jsfiddle.net/dtr7t4z7/1/
max-width : https://jsfiddle.net/dtr7t4z7/2/ and https://jsfiddle.net/dtr7t4z7/3/ max-widthhttps : //jsfiddle.net/dtr7t4z7/2/https://jsfiddle.net/dtr7t4z7/3/
min-width : https://jsfiddle.net/dtr7t4z7/4/ min-widthhttps : //jsfiddle.net/dtr7t4z7/4/

margin: auto will just fill the remaining space equally on both sides. margin: auto将仅在两侧均等地填充剩余空间。 If a width or max-width are not specified, a div will take up as much horizontal space as possible. 如果未指定widthmax-width则div将占用尽可能多的水平空间。 Because the div is the full width of its container when only min-width is specified, there isn't any space left for margin: auto to distribute. 因为当仅指定min-width时div是其容器的全宽,所以没有剩余空间供margin: auto分配。

https://jsfiddle.net/ehnvy1xz/5/ https://jsfiddle.net/ehnvy1xz/5/

body{
  display:flex;
  justify-content:center;
}
#line {
  text-align:center;
  background: yellow;
  min-width: 200px;
}

If you really need the min-width. 如果您确实需要最小宽度。 I would recommend using flex on the parent div and centering it that way instead. 我建议在父div上使用flex并以这种方式居中。

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

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