【问题标题】:make a div grow and shrink based on the browser window size根据浏览器窗口大小使 div 增长和缩小
【发布时间】:2012-12-19 19:23:39
【问题描述】:

我正在制作一个非常简单的 html 页面,想知道如何为我的页面做以下两件事:

  1. 我有一个容器 div,想将容器 div 放在页面的中心。
  2. 当我调整窗口大小时,容器 div 会增大和缩小。

我写了附加代码,但容器总是粘在左边,当我调整窗口大小时它不会改变大小。

<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>

我在这里错过了什么吗?任何帮助将不胜感激!

谢谢。

【问题讨论】:

  • 使用 % 大小,而不是 PX 大小,即width:80%;
  • 或者,最好不要浮动它。

标签: html css


【解决方案1】:
<div id="my-div">
  ...content goes here
</div>

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%;
}

【讨论】:

  • 我可以为&lt;header&gt;做吗?
【解决方案2】:

Matt 的 CSS 做水平居中的简写方法是

margin: 0 auto;

0 将指示顶部和底部边距,而 auto 将指示左右边距。如果您想要顶部/底部的边距,您可以将 0 更改为您想要的任何内容(即 margin: 20px auto; .

【讨论】:

    【解决方案3】:

    居中对象(尤其是&lt;div&gt;)的最佳方法是使用以下 CSS:

    margin-left: auto;
    margin-right: auto;
    

    没有固定边距,对象将居中。

    对于调整大小,使尺寸相对于页面(例如 40%)而不是绝对(例如 400 像素)。

    【讨论】:

      猜你喜欢
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多