css - div 中的 img 向左浮动,文本垂直和水平居中

标签 css html center

我觉得这应该(并且可能)在某个地方得到回答,但事实并非如此,我没有找到正确的方法,或者这是一些严密保护的国家 secret ,因为我找不到有效的答案。具体来说,我找不到适合我的 div 左侧图像的答案。

我想要实现的是让文本相对于整个屏幕水平居中,并在“标题”div 中垂直居中。我不想将我的 Logo 用作背景,因为我将其用作主播。我曾尝试使用“display: table-cell”和“vertical-align: middle”来获得灾难性的结果。请提供任何建议/帮助/链接。

CSS:

#header{
    width: 85%;
    min-width: 500px;
    text-align: center;
    margin-left: auto;
    margin-right: auto;
    overflow: hidden;
    background-color: #fff;
    border-bottom-width: 10px;
    border-bottom-style: double;
    border-bottom-color: #000;
}

#title{
    width: 85%;
    margin-left: auto;
    margin-right: auto;
    position: absolute;
    display: table-cell;
    vertical-align: middle;
}

#logo{
    float: left;
    padding-right: 1em;
    width: 150px;
}

HTML:

<div id="header">

      <a href="."><img id="logo" src="../images/logo.jpg" alt="Widget News" /></a>
    <span id="title"><h1>Site Title</h1></span>
      </div>

此外,我对使用 CSS 完全陌生(对 xhtml/html5 毫无用处)。我正在从事我当前的元素,以此来熟悉 CSS/PHP/HTML/JScript,到目前为止,CSS/HTML 是我遇到问题的唯一部分。任何指向好的初学者的指针,但不是补救/“傻瓜”指南,也将不胜感激。

最佳答案

我建议让您的 Logo 绝对定位。这将使它脱离 html 元素流(就像背景图像一样),同时保持它仍然可点击。

#logo {
position: absolute;
top: 5px;
left: 10px;
width: 150px;
}

这将使您的标题更容易居中。下面是对您的代码进行一些调整的完整示例:

http://jsfiddle.net/gqvUv/

您的“文本对齐:居中;”保持所有内容水平居中,调整 h1 的行高将使其垂直居中,只要标题只有一行。

相对定位和绝对定位很容易搞混,但本教程讲得很清楚:http://www.barelyfitz.com/screencast/html-training/css/positioning/

最后,这是我关于使用 CSS 居中的文章:http://designshack.net/articles/css/how-to-center-anything-with-css/

关于css - div 中的 img 向左浮动,文本垂直和水平居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15215856/

相关文章:

javascript - 字体大小变化问题

HTML & CSS : Align text line to bottom center of div

html - 如何悬停在子/嵌套 <li> 元素上

html - CSS 宽度和边距与媒体查询不相加

python - 使用 scrapy 抓取特定的表格元素

html - IE7 模式在多行左侧压缩表头内容

html - 如何在 float 旁边准确地将文本水平居中

html - 中心表单提交按钮 HTML/CSS

html - Bootstrap css : trying to work with offset, 但无法居中

css - 盒子大小 : border-box not working