Html 根据浏览器窗口大小使 div 增长和缩小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13959624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
make a div grow and shrink based on the browser window size
提问by Kintarō
I am making a very simple html page and would like to know how to do the following two things for my page:
我正在制作一个非常简单的 html 页面,想知道如何为我的页面做以下两件事:
- I have a container div and would like to put the container div in the center of the page.
- The container div will grow and shrink when I resize the windows size.
- 我有一个容器 div,想将容器 div 放在页面的中心。
- 当我调整窗口大小时,容器 div 将增长和缩小。
I wrote the attached code but the container is always sticked on the left and it won't change the size when I resize the window.
我写了附加的代码,但容器总是粘在左边,当我调整窗口大小时它不会改变大小。
<title>Demo</title>
<head>This is a demo</head>
<style>
#nav
{
background-color: red;
float: left;
width: 200px;
position:relative;
}
#detail
{
background-color: green;
float : right;
width: 800px;
position:relative;
}
div.testDetail
{
margin-top:10px;
margin-left:20px;
margin-right:20px;
margin-bottom:10px;
}
#container
{
width:1000px;
position:relative;
}
</style>
<hr>
<body>
<div id="container">
<div id="nav">
<ul>Tests</ul>
</div>
<div id="detail">
<div class="testDetail">
<image style="float:right;margin:5px;" src="test1.jpg" width="50px" height="50px"/>
<image style="float:right;margin:5px;" src="test2.jpg" width="50px" height="50px"/>
<image style="float:right;margin:5px;" src="test3.jpg" width="50px" height="50px"/>
<image style="float:right;margin:5px;" src="test4.jpg" width="50px" height="50px"/>
<h3>Title</h3>
<p>Testing</p>
</div>
<hr>
</div>
</div>
<body>
Did I miss something here? Any help will be appreciate!
我在这里错过了什么吗?任何帮助将不胜感激!
Thanks.
谢谢。
采纳答案by Mudassir Ali
<div id="my-div">
...content goes here
</div>
CSS
CSS
#my-div{
//For center align
margin: 0 auto;
// For grow & shrink as per screen size change values as per your requirements
width: 80%;
height: 50%;
}
回答by LLong
A shorthand method of Matt's CSS to do the horizontal centering is
Matt 的 CSS 进行水平居中的速记方法是
margin: 0 auto;
The 0 will dictate the top and bottom margin's and the auto the left and right margins. If you want a margin on the top/bottom you can change the 0 to anything you want(ie margin: 20px auto;
.
0 将指定顶部和底部边距,自动指定左右边距。如果您想要顶部/底部的边距,您可以将 0 更改为您想要的任何内容(即margin: 20px auto;
.
回答by BennyMathison
The best way to center an object, especially a <div>
, is to use the following CSS:
将对象(尤其是 a )居中的最佳方法<div>
是使用以下 CSS:
margin-left: auto;
margin-right: auto;
Without a fixed margin, the object will be centered.
如果没有固定的边距,对象将居中。
For the resizing, make sizes relative (e.g. 40%) to the page rather than absolute (e.g. 400px).
对于调整大小,使尺寸相对于页面(例如 40%)而不是绝对(例如 400px)。