2

给定以下html:

<div class="body">    
    <div class="banner">
        <div class="name">
            <h2>
                <a href="http://www.example.com">
                    <span class="bold">Test Link</span><br/>
                </a>
            </h2>
        </div>
        <div class="title">
            <h3>A Connections Learning Partner Program</h3>
            <p>Quality online learning for high school students in Oakland County and surrounding counties.
            </p>
        </div>
        <div class="link">
            <a href="http://www.example.com">Learn More</a>
        </div>
    </div>
</div>

如何在不给出高度或宽度的情况下垂直对齐.link a(按钮) ?.link像这样...

在此处输入图像描述

这是我的小提琴

4

3 回答 3

1

这是您可以做到的一种方法。您的 HTML 很好,无需更改任何内容。

对于 CSS:

.body { width: 920px; }

.banner {
    background-color: #454545;
    border-bottom: 3px solid #F9F9F9;
    height: 100px;
    margin: 0 0 5px;
    padding: 0;
    display: table;
}

.banner > div {
    outline: 1px dotted yellow; /* optional to show cell edges... */
    display: table-cell;
}

.banner .name {
    width: 25%;
    vertical-align: top;
    padding-top: 25px; /* control top white space */
    text-align: center;
}

.banner .name h2 {
    color: #F9F9F9;
    max-height: 55px;
    text-transform: uppercase;
    margin: 0;
    padding: 0;
}

.banner .title {
    width: 50%;
    vertical-align: top;
    padding-top: 25px;
}

.banner .title h3 {
    font-size: 15px;
    font-weight: bold;
    line-height: 15px;
    margin: 0px 0 0 0;
    padding: 0;
}

.banner .title p {
    font-size: 12px;
    max-height: 35px;
    overflow: hidden;
    margin: 0;
    padding: 0;
}

.banner .link {
    width: 25%;
    vertical-align: middle;
    text-align: left; /* set to left, center or right as needed */
}

.banner .link a {
    margin-left: 25px; /* controls left offset */
    background-color: #FA9800;
    border-radius: 5px 5px 5px 5px;
    cursor: pointer;
    display: inline-block; /* use inline-block if you want to center element */
    font-size: 12px;
    font-weight: bold;
    height: 23px;
    line-height: 23px;
    text-align: center;
    text-decoration: none;
    width: 100px;
}

参见小提琴:http: //jsfiddle.net/audetwebdesign/jsG8F/

这是如何工作的

诀窍是display: table在您的.banner容器上使用,然后display: table-cell在您的子div元素上使用,并将 % 宽度分别设置为 25%、50%、25% 为.name, .title, .link.

然后,您可以使用vertical-aligntext-align来控制各种文本块的垂直和水平放置。

我添加了与使用padding-top来控制横幅顶部的空白相关的评论。

对于.link a元素,您可以根据需要调整左边距(或右边距)。

这些 CSS 规则让您可以很好地控制横幅中各种元素的位置。

向后兼容性

display: table-cell属性向后兼容回 IE8。

参考:https ://developer.mozilla.org/en-US/docs/Web/CSS/display

于 2013-07-25T20:55:08.127 回答
0

Marc Audet 非常接近,但我最终选择了一条略有不同的路线。

我给了.link a一个固定的上边距,margin-left: auto;然后margin-right: auto;就成功了。

这是小提琴供参考。

于 2013-07-26T15:14:47.810 回答
0

如果元素和横幅的大小是固定的,则使用margin-top来偏移元素。

于 2013-07-25T20:34:34.053 回答