html - 试图将一个 div 标签置于一个 section 标签的中心

标签 html css

我似乎无法将我的 div 标签置于 section 标签的中心。我可以让它从左到右居中,但不是顶部和底部在部分标签的中心。如果我给出 margin-top:xxpx 然后它会向下移动 section 标签并暴露它(不好!)

这是我的CSS

body 
{
background-color: yellow;
margin: 0;
}

header > * {
margin: 0;
float: left;
}

header
{
background-color: white ;
width: 100%;
height: 40px;
}

/*header > input {
margin: 10px 20px 0px 10px;
}*/

#toptext
{
margin: 10px 5px 0px 10px;
width: 245px;
}

article > * {
margin: 0;
}

article
{
background-color: red;
}

#search {
background-color: #a6dbed;
height: 500px;
}

#middlesearch {
background-color: grey;
width: 700px;
margin: 0 auto;   
}

#mostdesired 
{
background-color: #c7d1d6;
height: 200px;
}

section h2 {
margin:0;
}

.site-title {
color: #c8c8c8;
font-family: Rockwell, Consolas, "Courier New", Courier, monospace;
font-size: 1.3em;
margin: 0px 20px 0px 50px;
margin-top: 7px;
}

.site-title a, .site-title a:hover, .site-title a:active {
background: none;
color: #c8c8c8;
outline: none;
text-decoration: none;
}

这是我的html

<body>
    <header>
        <p class="site-title">@Html.ActionLink("Site", "Index", "Home")</p>
        <input id="toptext" type="text" />
    </header>
    <article>
        <section id="search">
            <div id="middlesearch">
                <h2>Search Here</h2>@RenderBody()
            </div>
        </section>
        <section id="mostdesired" ><h2>This is the most section</h2></section>
    </article>
</body>

最佳答案

用 CSS 垂直对齐是出了名的棘手。

将 CSS 更改为

#search {
    position: relative;
    background-color: #a6dbed;
    height: 500px;
}

#middlesearch {
    position: absolute;
    background-color: grey;
    width: 700px;

    top: 50%;
    left: 50%;
    margin-left: -350px; /* half the width */
}

并添加一行 JQuery 来使 div 正确居中

$('#middlesearch').css("margin-top",-$('#middlesearch').height()/2)

如果您决定显式指定 div 的高度,则可以避免此行,此时您可以简单地在 CSS 中定义上边距。

这避免了必须使用表格。

关于html - 试图将一个 div 标签置于一个 section 标签的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24025513/

相关文章:

css - 如何在lesscss中主题化

css - 如何在 2 中编译 2 个 less 文件 !!! css文件在特定的地方?

javascript - 如何使用脚本更改第 n 类图像的宽度?

html - 许多人不知道如何在 HTML <select> 控件中多选项目,所以......?

javascript - if 语句 getElementById.src

php - 浏览器忽略/覆盖 CSS block

javascript - 变换 : rotate(); throws warnings in firefox

html - 在 Eclipse IDE 之外使用 JSP 文件

javascript - 如何在滚动条上播放暂停视频

html - 是否可以只用 CSS 而不用 JavaScript 来做到这一点?