将 div 中的两个元素垂直居中 [英] Vertically center two elements within a div

查看:26
本文介绍了将 div 中的两个元素垂直居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试垂直居中两个 <p> 元素.

我遵循了 phrogz.net 上的教程,但仍然放置了元素在 div 上方,在 div 下方,在 div 内顶部对齐.

我会尝试其他方法,但这里的大多数问题都指向那个教程.

此代码段用于网页顶部的横幅.

.banner {宽度:980px;高度:69px;背景图片:url(../images/nav-bg.jpg);背景重复:不重复;/* 颜色:#ffffff;*/}.bannerleft {向左飘浮;宽度:420px;文本对齐:右;高度:652px;行高:52px;字体大小:28px;padding-right: 5px;}.bannerright {浮动:对;宽度:555px;文本对齐:左;位置:相对;}.bannerrightinner {位置:绝对;顶部:50%;高度:52px;边距顶部:-26px;}

<div class="bannerright"><div class="bannerrightinner"><p>我应该是</p><p>垂直居中</p>

<div class="clear">

解决方案

添加以下内容:显示:表;到bannerRight

显示:表格单元格;和垂直对齐:中间;到bannerrightinner

我没有试过这个,如果它不起作用请给我反馈.;)

忘记提及:关闭浮动"和位置"属性

I am trying to vertically center two <p> elements.

I followed the tutorial at phrogz.net but still the elements get placed above the div, below the div, top-aligned within the div.

I would try something else but most of the questions here just point back to that tutorial.

This snippet is for a banner that is on the top of a web page.

.banner {
  width: 980px;
  height: 69px;
  background-image: url(../images/nav-bg.jpg);
  background-repeat: no-repeat;
  /* color: #ffffff; */
}

.bannerleft {
  float: left;
  width: 420px;
  text-align: right;
  height: 652px;
  line-height: 52px;
  font-size: 28px;
  padding-right: 5px;
}

.bannerright {
  float: right;
  width: 555px;
  text-align: left;
  position: relative;
}

.bannerrightinner {
  position: absolute;
  top: 50%;
  height: 52px;
  margin-top: -26px;
}

<div class="banner">
  <div class="bannerleft">
    I am vertically centered
  </div>
  <div class="bannerright">
    <div class="bannerrightinner">
      <p>I should be</p>
      <p>vertically centered</p>
    </div>
  </div>
  <div class="clear">
  </div>
</div>

解决方案

Add the following: display:table; to bannerRight

display:table-cell; and vertical-align:middle; to bannerrightinner

I have not tried this, please give me feedback if it does not work. ;)

EDIT: forgot to mention: take 'float' and 'position' properties off

这篇关于将 div 中的两个元素垂直居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆