[英]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-width
和min-width
过去,我们必须将width
设置为auto
以外的其他值,并将margin-left
和margin-right
为auto
,以使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-width
和min-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/ width
: https : //jsfiddle.net/dtr7t4z7/1/
max-width
: https://jsfiddle.net/dtr7t4z7/2/ and https://jsfiddle.net/dtr7t4z7/3/ max-width
: https : //jsfiddle.net/dtr7t4z7/2/和https://jsfiddle.net/dtr7t4z7/3/
min-width
: https://jsfiddle.net/dtr7t4z7/4/ min-width
: https : //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. 如果未指定
width
或max-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.