代码之家  ›  专栏  ›  技术社区  ›  user2252219

垂直对齐div

  •  0
  • user2252219  · 技术社区  · 11 年前

    我似乎无法使图像和文本在主分区内垂直对齐。

    https://jsfiddle.net/jf2dgh0j/

    .image {
    width:50%;
    height:auto;
    float:right;
    vertical-align:middle; }
    
    4 回复  |  直到 11 年前
        1
  •  1
  •   Marc Audet    11 年前

    我不确定为什么在父div的顶部有200px的填充,但以下可能是您正在尝试实现的。

    申请 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>
        2
  •  0
  •   Ben Fried    11 年前

    有些人反对桌子,但老实说,这正是桌子的用途。你的 div 只需向 td 的。修改了fiddle,使用表代替下面的div:

    https://jsfiddle.net/jjsx2t6e/

    我发现大多数东西都是垂直排列的,桌子真的是你的朋友,让生活变得更轻松。

        3
  •  0
  •   CupawnTae    11 年前

    你有一些不同的造型方法。如果您想使用 display: table 要对齐对象,不要同时使用 float 或 position: absolute .

    我不是100%清楚你想要实现什么,但下面的CSS垂直居中显示文本和图像分割。如果希望它们位于父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/

        4
  •  0
  •   HTron    11 年前

    我不完全确定“让图像和文本在主div内垂直对齐”是什么意思。我知道你希望文本和图像都垂直居中。

    首先是桌子。 然后在表的内部是表单元格。这应该具有父元素的100%宽度和100%高度。在那里设置垂直对齐:中心;所有物带有display:inline块的表单元格中的每个元素都将对齐。

    .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%;}
    

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