javascript - 居中的 div 锁定到位,不能上下移动

标签 javascript jquery html css

好吧,我有一个简单的网站,顶部居中有一个 100 像素的大 H1 标题,我有一个 h2 和下面的一段,都居中。

这些都排列得很好。

问题是,h2 和 p 位于透明黑色的 div 中,以便在背景下轻松阅读,并且它离 h1 标题有点太远了。 div 本身被锁定到位,h2 和 p 当然在 div 内部。我想将 div 向上移动一点,但无论我如何更改 top 属性它都不会移动。

*注意:h1 根本不在 div 内,也不在标题标签内。它就在 body 标签中。

我对此进行了相当多的研究,有人告诉我将锁定到位的 div 的位置更改为绝对位置或相对位置,但似乎所做的只是使 div 及其内部的所有内容都不居中了,它仍然以其他方式锁定在原地。该网站的代码有点长,所以我将包含问题中涉及的每个元素的 html 布局和 css。如果您需要更多帮助,请告诉我 :)

html:

<body class="home-page">
    <h1>Visit Montana</h1>
    <div class="navbar">
        <a href="home.html">
            <button id="home">
                home
            </button>
        </a>
        <a href="dining.html">
            <button id="dining">
                dining
            </button>
        </a>
        <a href="entertainment.html">
            <button id="entertainment">
                entertainment
            </button>
        </a>
        <a href="lodging.html">
            <button id="lodging">
                lodging
            </button>
        </a>
    </div>
    <div class="main-body">
        <h2>
            Why Visit Montana?
        </h2>
        <p>
            words (I modified this so it wouldn't be a wall of text. There     are 200 words here)
        </p>
    </div>
</body>

CSS:

h1{
        text-align:center;
        color:white;
        position:relative;
        font-size:100px;
        font-family: 'Poiret One', cursive;
        padding:0;
        z-index:6;      
    }

h2{
        font-size:50px;
        text-align:center;
        color:white;
         position:relative;
        font-family: 'Poiret One', cursive;
        padding:20px 0px 0px 0px;
    }

p{
    font-size:30px;
    text-align:left;
    color:white;
    position:relative;
    font-family: 'Poiret One', cursive;
    padding:0px 40px 0px 40px;
}

.main-body{
    background-color:rgba(15, 15, 15, 0.57);
    height:425px;
    width:1100px;
    margin-left: auto;
    margin-right: auto; 
}

最佳答案

首先,您应该删除浏览器的所有默认填充和边距。为此使用以下内容。

* {
    margin: 0;
    padding: 0;
}

然后你可以将 margin-top.main-body div 来上下移动它们。

.main-body {
    background-color: rgba(15, 15, 15, 0.57);
    height: 425px;
    margin-left: auto;
    margin-right: auto;
    margin-top: 20px; //Here.
    width: 1100px;
}

这里我给 margin-top:20px。您可以根据需要更改它。

Working Fiddle

关于javascript - 居中的 div 锁定到位,不能上下移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35403014/

相关文章:

javascript - 更改模板标签后 John Resig 的微模板出现语法错误 <# {% {{ 等

javascript - 允许输入最多 3 位小数

html - 一个输入字段,多个名称

java - 删除一些 HTML 标签但保留 Span 标签的正则表达式

javascript - 在哪里可以找到要添加到 babel.config.js 的 polyfill 名称

javascript - 如何让 fabricJS 处理触摸事件?

javascript - javascript中如何处理大数字

php - 如何使用 ajax 从 CodeIgniter 中动态生成的表单上传图像

javascript - Javascript/jQuery 中类似 MVC 的 UI 更新 : best practices?

javascript - 更改多个输入的值