垂直对齐 div

Vertically aligning div

我似乎无法让图像和文本在主 div 中垂直对齐。

https://jsfiddle.net/jf2dgh0j/

.image {
width:50%;
height:auto;
float:right;
vertical-align:middle; }

有些人反对 table,但老实说,这正是 table 的目的。您的 div 只是变成了 td。使用 table 而不是下面的 div 修改 fiddle:

https://jsfiddle.net/jjsx2t6e/

我发现大多数东西都是垂直对齐的,table它真的是你的朋友,让生活变得更轻松。

您混合使用了不同的样式方法。如果你想使用 display: table 来对齐,不要同时使用 floatposition: absolute

我不是 100% 清楚您要实现的目标,但下面的 CSS 将文本和图像 div 垂直居中。如果您希望它们在父项中居中 div,您还需要调整填充。

.image {
    width: 50%;
    display: table-cell;
    vertical-align: middle;
}
.description-wrap {
    background-color: #fff;
    display: table-cell;
    vertical-align: middle
}

已更新 fiddle https://jsfiddle.net/jf2dgh0j/1/

我不确定为什么你在父级的顶部有 200 像素的填充 div,但以下可能是你想要实现的。

display: table-cell 应用于 .description-wrap.image 子元素。

.work-subwrap {
    width:70%;
    background-color:#C87778;
    margin:0 auto;
    margin-top:30px;
    display:table;
}
.description-wrap, .image {
    display: table-cell;
    width: 50%;
    vertical-align: middle;
    text-align: center;
}
.description-wrap a {
    display: inline-block;
    padding: 10px;
    background-color: white;
}
.image img {
    width:100%;
    vertical-align: top;
}
<div class="work-subwrap">
    <div class="description-wrap"> <a class="project-link" href="#modal1">Maru</a></div>
    <div class="image">
        <img alt="" id="first" src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQdiIK0bVvSbRnegxQPMS6V0nBHFT40j6P6OH-C11pmooy6Duad">
    </div>
</div>

我不完全确定 "get both the image and text to align vertically inside the main div" 是什么意思。我了解到您希望文本和图像都垂直居中。

首先是 table。 然后在 table 里面有 table 单元格。这应该有父元素的 100% 宽度和 100% 高度。在那里你设置了垂直对齐:中心; 属性。 table-cell 和 display:inline-block 中的每个元素都将对齐。

.work-subwrap {
    width:70%;
    height:500px;
    background-color:#C87778;
    margin:0 auto;
    margin-top:30px;
    position:relative;
    display:table;
}
.image {
    display:table-cell;
    width:100%;
    height:auto;
    vertical-align:middle;
    text-align:center;
}
.description-wrap {
    display:inline-block;
    background-color:#fff;
    position:absolute;
    top:50%;
    left:50%;
    -webkit-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
}

.image img {width:50%;}

只要文本 / link 没有固定的宽度/高度,我建议使用 translate() 相对固定它的位置。它的缺点是它并不总是与旧浏览器兼容。