好的,我有一个简单的网站,顶部有一个大100px的H1标头,下面有一个h2和一个段落,都居中。

这些都很好地排列在一起。

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

*注意:h1根本不在div内,也不在标头标记内。它只是在身体标签中。

我对此进行了相当多的研究,有人告诉我将锁定在适当位置的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

08-18 22:07
查看更多