OK, I have a div that is in the centred:
好的,我有一个居中的div:
<div id="spry">
<p> hello there asdsdfasd adsfasdf aasdfasfd </p>
</div>
Uses this CSS:
使用这个CSS:
#spry {
background-color: red;
display: block;
margin-left: auto;
margin-right: auto;
width: 400px;
}
But I want to have the div not a fixed width. I figured I could just change width: 400px
; to width: auto;
但我希望div不是固定的宽度。我想我可以改变宽度:400px;宽度:自动;
But if you do that it just expands to the whole width.
但如果你这样做,它只会扩展到整个宽度。
3 个解决方案
#1
3
You can change the display value to inline-block
and then use text-align: center;
on its parent container (though since it doesn't have one I just used the <body>
as an example):
您可以将显示值更改为内联块,然后使用text-align:center;在它的父容器上(虽然它没有一个我只使用作为例子):
body {
text-align: center;
}
#spry {
background-color: red;
display: inline-block;
}
#2
1
You can use max-width
- This essentially says don't be anymore than 400pixels but you can be smaller. Try resizing the window.
你可以使用max-width - 这基本上说不要超过400像素,但你可以更小。尝试调整窗口大小。
This is a good option if you do not want a fixed width. Alternatively you could try a percentage, then just use max-width
to define a maximum width that you desire.
如果您不想要固定宽度,这是一个不错的选择。或者,你可以尝试一个百分比,然后只需使用max-width来定义你想要的最大宽度。
You can see the width displayed as you resize just to demonstrate
您可以在调整大小时看到显示的宽度以进行演示
#3
-1
try margin:0 auto;
see what happens
尝试保证金:0自动;走着瞧吧
#1
3
You can change the display value to inline-block
and then use text-align: center;
on its parent container (though since it doesn't have one I just used the <body>
as an example):
您可以将显示值更改为内联块,然后使用text-align:center;在它的父容器上(虽然它没有一个我只使用作为例子):
body {
text-align: center;
}
#spry {
background-color: red;
display: inline-block;
}
#2
1
You can use max-width
- This essentially says don't be anymore than 400pixels but you can be smaller. Try resizing the window.
你可以使用max-width - 这基本上说不要超过400像素,但你可以更小。尝试调整窗口大小。
This is a good option if you do not want a fixed width. Alternatively you could try a percentage, then just use max-width
to define a maximum width that you desire.
如果您不想要固定宽度,这是一个不错的选择。或者,你可以尝试一个百分比,然后只需使用max-width来定义你想要的最大宽度。
You can see the width displayed as you resize just to demonstrate
您可以在调整大小时看到显示的宽度以进行演示
#3
-1
try margin:0 auto;
see what happens
尝试保证金:0自动;走着瞧吧