如何垂直对齐 div 中的元素?

发布于 2024-07-04 19:57:16 字数 370 浏览 9 评论 0原文

我有一个包含两个图像的 div 和一个 h1。 所有这些都需要在 div 内垂直对齐,彼此相邻。 其中一张图像需要绝对定位在div内。

需要什么 CSS 才能在所有常见浏览器上运行?

<div id="header">
  <img src=".." ></img>
  <h1>testing...</h1>
  <img src="..."></img>
</div>

I have a div with two images and an h1. All of them need to be vertically aligned within the div, next to each other. One of the images needs to be absolute positioned within the div.

What is the CSS needed for this to work on all common browsers?

<div id="header">
  <img src=".." ></img>
  <h1>testing...</h1>
  <img src="..."></img>
</div>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

过潦 2024-07-11 19:57:16

将 child(div) 居中对齐的四种方法。

  • 绝对定位法
  • Flexbox 法
  • 变换/平移法
  • CSS 网格法

浏览器支持 CSS 网格

在此处输入图像描述

演示

/* Absolute Positioning Method */
.parent1 {
  background: darkcyan;
   width: 150px;
   height: 150px;
   position: relative;
}
.child1 {
  background: white;
  height: 30px;
  width: 30px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -15px;
}

/* Flexbox Method */
.parent2 {
  display: flex;
  justify-content: center;
  align-items: center;
  background: darkcyan;
  width: 150px;
  height: 150px;
}
.child2 {
  background: white;
  height: 30px;
  width: 30px;
}

/* Transform/Translate Method */
.parent3 {
  position: relative;
  width: 150px;
  height: 150px;
  background: darkcyan;
}
.child3 {
  background: white;
  height: 30px;
  width: 30px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* CSS grid */
.parent4, .parent5 {
  position: relative;
  width: 150px;
  height: 150px;
  background: darkcyan;
  display: grid;
  place-items: center;
}
.child4, .child5 {
  background: white;
  height: 30px;
  width: 30px;
}
.parent5 {
  display: grid;
  justify-items: centre;
  align-content: centre;
}
<div class="parent1">
  <div class="child1"></div>
</div>
<hr />

<div class="parent2">
  <div class="child2"></div>
</div>
<hr />

<div class="parent3">
  <div class="child3"></div>
</div>
<hr />

<div class="parent4">
  <div class="child4"></div>
</div>
<hr />

<div class="parent5">
  <div class="child5"></div>
</div>

Four ways to to align child(div) in center.

  • Absolute positioning method
  • Flexbox method
  • Transform/translate method
  • CSS grid method

Browser support for CSS grid

Enter image description here

Demo

/* Absolute Positioning Method */
.parent1 {
  background: darkcyan;
   width: 150px;
   height: 150px;
   position: relative;
}
.child1 {
  background: white;
  height: 30px;
  width: 30px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -15px;
}

/* Flexbox Method */
.parent2 {
  display: flex;
  justify-content: center;
  align-items: center;
  background: darkcyan;
  width: 150px;
  height: 150px;
}
.child2 {
  background: white;
  height: 30px;
  width: 30px;
}

/* Transform/Translate Method */
.parent3 {
  position: relative;
  width: 150px;
  height: 150px;
  background: darkcyan;
}
.child3 {
  background: white;
  height: 30px;
  width: 30px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* CSS grid */
.parent4, .parent5 {
  position: relative;
  width: 150px;
  height: 150px;
  background: darkcyan;
  display: grid;
  place-items: center;
}
.child4, .child5 {
  background: white;
  height: 30px;
  width: 30px;
}
.parent5 {
  display: grid;
  justify-items: centre;
  align-content: centre;
}
<div class="parent1">
  <div class="child1"></div>
</div>
<hr />

<div class="parent2">
  <div class="child2"></div>
</div>
<hr />

<div class="parent3">
  <div class="child3"></div>
</div>
<hr />

<div class="parent4">
  <div class="child4"></div>
</div>
<hr />

<div class="parent5">
  <div class="child5"></div>
</div>

横笛休吹塞上声 2024-07-11 19:57:16

我尝试使用 CSS flex 来做到这一点,但如果它超出了块(使用“overflow:auto”),它就会截断对象

通过实验,我发现如果使用网格,很容易将任何对象(线或块)居中。

我真的很喜欢这个解决方案,所以我在 CMS Effcore 中实现了它。

这是一个代码示例:

<head>
    <style>
        [data-id^='example-'] {
          max-width: 800px;
          height: 200px;
          margin: 20px auto;
          background: gray;
        }
        [data-id^='example-'] img {
          width: 50px;
          height: 50px;
          border: 1px solid black;
          background: gray;
        }
    </style>
</head>
<body>
    <div data-id="example-1">
        <img src="gallery/pictures/thumbnail-01.png">
    </div>
    <div data-id="example-2">
        <img src="gallery/pictures/thumbnail-01.png">
    </div>
    <div data-id="example-3">
        <img src="gallery/pictures/thumbnail-01.png">
    </div>
</body>
</html>

通过网格的示例:

/*
┌─────┬───────────────────────┬─────┐
│ 1fr │          1fr          │ 1fr │
├─────┼───────────────────────┼─────┤
│     │  ▲                    │     │
│     │ ◀┼──────────────────▶ │     │
│ 1fr │  │ 1px|max-content    │ 1fr │
│     │  │                    │     │
│     │  ▼                    │     │
├─────┼───────────────────────┼─────┤
│ 1fr │          1fr          │ 1fr │
└─────┴───────────────────────┴─────┘
*/

[data-id='example-1'] {
  display: grid;
  grid-template-columns: 1fr minmax(1px, max-content) 1fr;
  grid-template-rows   : 1fr minmax(1px, max-content) 1fr;
}

[data-id='example-1'] img {
  grid-column-start: 2;
  grid-row-start:    2;
}

通过“flex”的示例。

[data-id='example-2'] {
  display: flex;
  align-items: center;
}

[data-id='example-2'] img {
  margin: 0 auto;
}

通过“垂直对齐”的示例。

[data-id='example-3'] {
  text-align: center;
  white-space: nowrap;
}

[data-id='example-3']:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

[data-id='example-3'] img {
  vertical-align: middle;
}

可以在此处找到实时代码示例: https://developer.mozilla .org/ru/play?id=AE9iTZBMsHnSmr4lfRPvmQU3p6DMFO4uGxZY%2BM7ABDgHuUotnvJdG5VISHO5%2BkYdb7YGTMQtKr2HlhGc

I tried to do it using CSS flex but it truncates the object if it goes beyond the block (with "overflow: auto").

Through experimentation, I discovered that it is very easy to center any object (line or block) if you use Grid.

I really liked the solution, so I implemented it in the CMS Effcore.

Here is a code example:

<head>
    <style>
        [data-id^='example-'] {
          max-width: 800px;
          height: 200px;
          margin: 20px auto;
          background: gray;
        }
        [data-id^='example-'] img {
          width: 50px;
          height: 50px;
          border: 1px solid black;
          background: gray;
        }
    </style>
</head>
<body>
    <div data-id="example-1">
        <img src="gallery/pictures/thumbnail-01.png">
    </div>
    <div data-id="example-2">
        <img src="gallery/pictures/thumbnail-01.png">
    </div>
    <div data-id="example-3">
        <img src="gallery/pictures/thumbnail-01.png">
    </div>
</body>
</html>

Example via Grid:

/*
┌─────┬───────────────────────┬─────┐
│ 1fr │          1fr          │ 1fr │
├─────┼───────────────────────┼─────┤
│     │  ▲                    │     │
│     │ ◀┼──────────────────▶ │     │
│ 1fr │  │ 1px|max-content    │ 1fr │
│     │  │                    │     │
│     │  ▼                    │     │
├─────┼───────────────────────┼─────┤
│ 1fr │          1fr          │ 1fr │
└─────┴───────────────────────┴─────┘
*/

[data-id='example-1'] {
  display: grid;
  grid-template-columns: 1fr minmax(1px, max-content) 1fr;
  grid-template-rows   : 1fr minmax(1px, max-content) 1fr;
}

[data-id='example-1'] img {
  grid-column-start: 2;
  grid-row-start:    2;
}

Example via "flex".

[data-id='example-2'] {
  display: flex;
  align-items: center;
}

[data-id='example-2'] img {
  margin: 0 auto;
}

Example via "vertical-align".

[data-id='example-3'] {
  text-align: center;
  white-space: nowrap;
}

[data-id='example-3']:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

[data-id='example-3'] img {
  vertical-align: middle;
}

A live code example can be found here: https://developer.mozilla.org/ru/play?id=AE9iTZBMsHnSmr4lfRPvmQU3p6DMFO4uGxZY%2BM7ABDgHuUotnvJdG5VISHO5%2BkYdb7YGTMQtKr2HlhGc

初见终念 2024-07-11 19:57:16

就是这样:

<div>
    <table style="width: 100%; height: 100%">
        <tr>
            <td style="width: 100%; height: 100%; vertical-align: middle;">
               What ever you want vertically-aligned
            </td>
        </tr>
    </table>
</div>

div 内的一个单元格表格处理垂直对齐,并且向后兼容回到石器时代!

Just this:

<div>
    <table style="width: 100%; height: 100%">
        <tr>
            <td style="width: 100%; height: 100%; vertical-align: middle;">
               What ever you want vertically-aligned
            </td>
        </tr>
    </table>
</div>

A one-cell table inside the div handles the vertical-align and is backward compatible back to the Stone Age!

猫性小仙女 2024-07-11 19:57:16
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
    <head>
        <style type="text/css">
            #style_center { position:relative; top:50%; left:50%; }
            #style_center_absolute { position:absolute; top:50px; left:50px; }
            <!--#style_center { position:relative; top:50%; left:50%; height:50px; margin-top:-25px; }-->
        </style>
    </head>

    <body>
        <div style="height:200px; width:200px; background:#00FF00">
            <div id="style_center">+</div>
        </div>
    </body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
    <head>
        <style type="text/css">
            #style_center { position:relative; top:50%; left:50%; }
            #style_center_absolute { position:absolute; top:50px; left:50px; }
            <!--#style_center { position:relative; top:50%; left:50%; height:50px; margin-top:-25px; }-->
        </style>
    </head>

    <body>
        <div style="height:200px; width:200px; background:#00FF00">
            <div id="style_center">+</div>
        </div>
    </body>
</html>
不再见 2024-07-11 19:57:16

这是另一种(响应式)方法:

html,
    body {
        height: 100%;
    }
    body {
        margin: 0;
    }

    .table {
        display: table;
        width:  auto;
        table-layout:auto;
        height: 100%;
    }
        .table:nth-child(even) {
            background: #a9edc3;
        }
        .table:nth-child(odd) {
            background: #eda9ce;
        }

    .tr {
        display: table-row;
    }
    .td {
        display: table-cell;
        width: 50%;
        vertical-align: middle;
    }

http://jsfiddle.net/herrfischerhamburg/JcVxz/

Here is just another (responsive) approach:

html,
    body {
        height: 100%;
    }
    body {
        margin: 0;
    }

    .table {
        display: table;
        width:  auto;
        table-layout:auto;
        height: 100%;
    }
        .table:nth-child(even) {
            background: #a9edc3;
        }
        .table:nth-child(odd) {
            background: #eda9ce;
        }

    .tr {
        display: table-row;
    }
    .td {
        display: table-cell;
        width: 50%;
        vertical-align: middle;
    }

http://jsfiddle.net/herrfischerhamburg/JcVxz/

情深如许 2024-07-11 19:57:16
<div id="header" style="display: table-cell; vertical-align:middle;">

...

或 CSS

.someClass
{
   display: table-cell;
   vertical-align:middle;
}

浏览器覆盖范围

<div id="header" style="display: table-cell; vertical-align:middle;">

...

or CSS

.someClass
{
   display: table-cell;
   vertical-align:middle;
}

Browser Coverage

九八野马 2024-07-11 19:57:16

我已经使用以下解决方案(没有定位和行高)一年多了。 它可与 Internet Explorer 7Internet Explorer 8 也是如此。

<style>
.outer {
    font-size: 0;
    width: 400px;
    height: 400px;
    background: orange;
    text-align: center;
    display: inline-block;
}

.outer .emptyDiv {
    height: 100%;
    background: orange;
    visibility: collapse;
}

.outer .inner {
    padding: 10px;
    background: red;
    font: bold 12px Arial;
}

.verticalCenter {
    display: inline-block;
    *display: inline;
    zoom: 1;
    vertical-align: middle;
}
</style>

<div class="outer">
    <div class="emptyDiv verticalCenter"></div>
    <div class="inner verticalCenter">
        <p>Line 1</p>
        <p>Line 2</p>
    </div>
</div>

I have been using the following solution (with no positioning and no line height) for over a year. It works with Internet Explorer 7 and Internet Explorer 8 as well.

<style>
.outer {
    font-size: 0;
    width: 400px;
    height: 400px;
    background: orange;
    text-align: center;
    display: inline-block;
}

.outer .emptyDiv {
    height: 100%;
    background: orange;
    visibility: collapse;
}

.outer .inner {
    padding: 10px;
    background: red;
    font: bold 12px Arial;
}

.verticalCenter {
    display: inline-block;
    *display: inline;
    zoom: 1;
    vertical-align: middle;
}
</style>

<div class="outer">
    <div class="emptyDiv verticalCenter"></div>
    <div class="inner verticalCenter">
        <p>Line 1</p>
        <p>Line 2</p>
    </div>
</div>
笑着哭最痛 2024-07-11 19:57:16

使用display flex,首先需要包装要对齐的项目的容器:

<div class="outdiv">
    <div class="indiv">
        <span>test1</span>
        <span>test2</span>
    </div>
</div>

然后应用以下CSS内容来包装我的示例中的divoutdiv

.outdiv {
    display: flex;
    justify-content: center;
    align-items: center;
}

Using display flex, first you need to wrap the container of the item that you want to align:

<div class="outdiv">
    <div class="indiv">
        <span>test1</span>
        <span>test2</span>
    </div>
</div>

Then apply the following CSS content to wrap div or outdiv in my example:

.outdiv {
    display: flex;
    justify-content: center;
    align-items: center;
}
许仙没带伞 2024-07-11 19:57:16

使用CSS垂直居中,您可以让外部容器像表格一样,而内容像表格单元格一样。 在这种格式中,您的对象将保持居中。 :)

我在 JSFiddle 中嵌套了多个对象作为示例,但核心思想是这样的:

HTML

<div class="circle">
  <div class="content">
    Some text
  </div>
</div>

CSS

.circle {
  /* Act as a table so we can center vertically its child */
  display: table;
  /* Set dimensions */
  height: 200px;
  width: 200px;
  /* Horizontal center text */
  text-align: center;
  /* Create a red circle */
  border-radius: 100%;
  background: red;
}

.content {
  /* Act as a table cell */
  display: table-cell;
  /* And now we can vertically center! */
  vertical-align: middle;
  /* Some basic markup */
  font-size: 30px;
  font-weight: bold;
  color: white;
}

多个对象示例:

HTML

<div class="container">
  <div class="content">

    <div class="centerhoriz">

      <div class="circle">
        <div class="content">
          Some text
        </div><!-- content -->
      </div><!-- circle -->

      <div class="square">
        <div class="content">
          <div id="smallcircle"></div>
        </div><!-- content -->
      </div><!-- square -->

    </div><!-- center-horiz -->

  </div><!-- content -->
</div><!-- container -->

<强>CSS

.container {
  display: table;
  height: 500px;
  width: 300px;
  text-align: center;
  background: lightblue;
}

.centerhoriz {
  display: inline-block;
}

.circle {
  display: table;
  height: 200px;
  width: 200px;
  text-align: center;
  background: red;
  border-radius: 100%;
  margin: 10px;
}

.square {
  display: table;
  height: 200px;
  width: 200px;
  text-align: center;
  background: blue;
  margin: 10px;
}

.content {
  display: table-cell;
  vertical-align: middle;
  font-size: 30px;
  font-weight: bold;
  color: white;
}

#smallcircle {
  display: inline-block;
  height: 50px;
  width: 50px;
  background: green;
  border-radius: 100%;
}

结果

结果

https:/ /jsfiddle.net/martjemeyer/ybs032uc/1/

Using CSS to vertical center, you can let the outer containers act like a table, and the content as a table cell. In this format your objects will stay centered. :)

I nested multiple objects in JSFiddle for an example, but the core idea is like this:

HTML

<div class="circle">
  <div class="content">
    Some text
  </div>
</div>

CSS

.circle {
  /* Act as a table so we can center vertically its child */
  display: table;
  /* Set dimensions */
  height: 200px;
  width: 200px;
  /* Horizontal center text */
  text-align: center;
  /* Create a red circle */
  border-radius: 100%;
  background: red;
}

.content {
  /* Act as a table cell */
  display: table-cell;
  /* And now we can vertically center! */
  vertical-align: middle;
  /* Some basic markup */
  font-size: 30px;
  font-weight: bold;
  color: white;
}

The multiple objects example:

HTML

<div class="container">
  <div class="content">

    <div class="centerhoriz">

      <div class="circle">
        <div class="content">
          Some text
        </div><!-- content -->
      </div><!-- circle -->

      <div class="square">
        <div class="content">
          <div id="smallcircle"></div>
        </div><!-- content -->
      </div><!-- square -->

    </div><!-- center-horiz -->

  </div><!-- content -->
</div><!-- container -->

CSS

.container {
  display: table;
  height: 500px;
  width: 300px;
  text-align: center;
  background: lightblue;
}

.centerhoriz {
  display: inline-block;
}

.circle {
  display: table;
  height: 200px;
  width: 200px;
  text-align: center;
  background: red;
  border-radius: 100%;
  margin: 10px;
}

.square {
  display: table;
  height: 200px;
  width: 200px;
  text-align: center;
  background: blue;
  margin: 10px;
}

.content {
  display: table-cell;
  vertical-align: middle;
  font-size: 30px;
  font-weight: bold;
  color: white;
}

#smallcircle {
  display: inline-block;
  height: 50px;
  width: 50px;
  background: green;
  border-radius: 100%;
}

Result

Result

https://jsfiddle.net/martjemeyer/ybs032uc/1/

〗斷ホ乔殘χμё〖 2024-07-11 19:57:16

我找到了一种新的解决方法,可以使用 CSS 3 垂直对齐 div 中的多个文本行(并且我还使用 bootstrap v3 网格系统来美化 UI),如下所示:

.immediate-parent-of-text-containing-div {
    height: 50px;         /* Or any fixed height that suits you. */
}

.text-containing-div {
    display: inline-grid;
    align-items: center;
    text-align: center;
    height: 100%;
}

根据我的理解,包含元素的文本必须有一定的高度。

I have found a new workaround to vertically align multiple text-lines in a div using CSS 3 (and I am also using bootstrap v3 grid system to beautify the UI), which is as below:

.immediate-parent-of-text-containing-div {
    height: 50px;         /* Or any fixed height that suits you. */
}

.text-containing-div {
    display: inline-grid;
    align-items: center;
    text-align: center;
    height: 100%;
}

As per my understanding, the immediate parent of text containing element must have some height.

世界等同你 2024-07-11 19:57:16

这一天已经到来了!

块布局的 align-content 属性可用于对齐。

#outer {
  align-content: center;
  height: 100px;
  border: 1px solid grey;
}
<div id="outer">
   <div id="inner">CSS is awesome</div>
</div>

浏览器支持:

  • Chrome 123
  • Edge 123
  • Firefox 125
  • Safari 17.4

This day has come!

align-content property for block layouts can be used for aligning.

#outer {
  align-content: center;
  height: 100px;
  border: 1px solid grey;
}
<div id="outer">
   <div id="inner">CSS is awesome</div>
</div>

Browser Support:

  • Chrome 123
  • Edge 123
  • Firefox 125
  • Safari 17.4
南薇 2024-07-11 19:57:16

我们可以使用 CSS 函数计算来计算元素的大小,然后相应地定位子元素。

示例 HTML:

<div class="box">
    <span><a href="#">Some Text</a></span>
</div>

和 CSS:

.box {
    display: block;
    background: #60D3E8;
    position: relative;
    width: 300px;
    height: 200px;
    text-align: center;
}

.box span {
    font: bold 20px/20px 'source code pro', sans-serif;
    position: absolute;
    left: 0;
    right: 0;
    top: calc(50% - 10px);
}

a {
    color: white;
    text-decoration: none;
}

此处创建的演示: https://jsfiddle.net/xnjq1t22/

此解决方案有效以及响应式 div heightwidth

注意:calc 函数未测试与旧浏览器的兼容性。

We may use a CSS function calculation to calculate the size of the element and then position the child element accordingly.

Example HTML:

<div class="box">
    <span><a href="#">Some Text</a></span>
</div>

And CSS:

.box {
    display: block;
    background: #60D3E8;
    position: relative;
    width: 300px;
    height: 200px;
    text-align: center;
}

.box span {
    font: bold 20px/20px 'source code pro', sans-serif;
    position: absolute;
    left: 0;
    right: 0;
    top: calc(50% - 10px);
}

a {
    color: white;
    text-decoration: none;
}

Demo created here: https://jsfiddle.net/xnjq1t22/

This solution works well with responsive div height and width as well.

Note: The calc function is not tested for compatiblity with old browsers.

寄居者 2024-07-11 19:57:16

仅使用 Bootstrap 类:

  • div: class="container d-flex"
  • div 内的元素:class="m-auto"
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css" crossorigin="anonymous">

<div class="container d-flex mt-5" style="height:110px; background-color: #333;">
  <h2 class="m-auto"><a href="https://hovermind.com/">H➲VER➾M⇡ND</a></h2>
</div>

Using only a Bootstrap class:

  • div: class="container d-flex"
  • element inside div: class="m-auto"

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css" crossorigin="anonymous">

<div class="container d-flex mt-5" style="height:110px; background-color: #333;">
  <h2 class="m-auto"><a href="https://hovermind.com/">H➲VER➾M⇡ND</a></h2>
</div>

初雪 2024-07-11 19:57:16

默认情况下,h1 是一个块元素,将在第一个 img 之后的行上渲染,并将导致第二个 img 出现在块后面的行上。

要阻止这种情况发生,您可以将 h1 设置为具有内联流行为:

#header > h1 { display: inline; }

至于将 img 绝对定位在 div 内,您需要将包含的 div 设置为具有“已知大小”,然后才会出现这种情况。好好工作。 根据我的经验,您还需要更改位置属性,使其远离默认值 -position:relative 对我来说很有效:

#header { position: relative; width: 20em; height: 20em; }
#img-for-abs-positioning { position: absolute; top: 0; left: 0; }

如果您可以使其正常工作,您可能需要尝试逐步从 div.header 中删除高度、宽度、位置属性获得所需的最少属性以获得您想要的效果。

更新:

以下是适用于 Firefox 3 的完整示例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
              "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html>
        <head>
            <title>Example of vertical positioning inside a div</title>
            <style type="text/css">
                #header > h1 { display: inline; }
                #header { border: solid 1px red; 
                          position: relative; }
                #img-for-abs-positioning { position: absolute;
                                           bottom: -1em; right: 2em; }
            </style>
        </head>
    
        <body>
            <div id="header">
                <img src="#" alt="Image 1" width="40" height="40" />
                <h1>Header</h1>
                <img src="#" alt="Image 2" width="40" height="40" 
                     id="img-for-abs-positioning" />
            </div>
        </body>
    </html>

By default h1 is a block element and will render on the line after the first img, and will cause the second img to appear on the line following the block.

To stop this from occurring you can set the h1 to have inline flow behaviour:

#header > h1 { display: inline; }

As for absolutely positioning the img inside the div, you need to set the containing div to have a "known size" before this will work properly. In my experience, you also need to change the position attribute away from the default - position: relative works for me:

#header { position: relative; width: 20em; height: 20em; }
#img-for-abs-positioning { position: absolute; top: 0; left: 0; }

If you can get that to work, you might want to try progressively removing the height, width, position attributes from div.header to get the minimal required attributes to get the effect you want.

UPDATE:

Here is a complete example that works on Firefox 3:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
              "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html>
        <head>
            <title>Example of vertical positioning inside a div</title>
            <style type="text/css">
                #header > h1 { display: inline; }
                #header { border: solid 1px red; 
                          position: relative; }
                #img-for-abs-positioning { position: absolute;
                                           bottom: -1em; right: 2em; }
            </style>
        </head>
    
        <body>
            <div id="header">
                <img src="#" alt="Image 1" width="40" height="40" />
                <h1>Header</h1>
                <img src="#" alt="Image 2" width="40" height="40" 
                     id="img-for-abs-positioning" />
            </div>
        </body>
    </html>

人间不值得 2024-07-11 19:57:16

我最喜欢的新方法是使用 CSS 网格:

/* technique */

.wrapper {
  display: inline-grid;
  grid-auto-flow: column;
  align-items: center;
  justify-content: center;
}

/* visual emphasis */

.wrapper {
  border: 1px solid red;
  height: 180px;
  width: 400px;
}

img {
  width: 100px;
  height: 80px;
  background: #fafafa;
}

img:nth-child(2) {
  height: 120px;
}
<div class="wrapper">
  <img src="https://source.unsplash.com/random/100x80/?bear">
  <img src="https://source.unsplash.com/random/100x120/?lion">
  <img src="https://source.unsplash.com/random/100x80/?tiger">
</div>

My new favorite way to do it is with a CSS grid:

/* technique */

.wrapper {
  display: inline-grid;
  grid-auto-flow: column;
  align-items: center;
  justify-content: center;
}

/* visual emphasis */

.wrapper {
  border: 1px solid red;
  height: 180px;
  width: 400px;
}

img {
  width: 100px;
  height: 80px;
  background: #fafafa;
}

img:nth-child(2) {
  height: 120px;
}
<div class="wrapper">
  <img src="https://source.unsplash.com/random/100x80/?bear">
  <img src="https://source.unsplash.com/random/100x120/?lion">
  <img src="https://source.unsplash.com/random/100x80/?tiger">
</div>

是伱的 2024-07-11 19:57:16

只需在 div 内使用一个单元格表格即可! 只需将单元格和表格的高度设置为 100%,即可使用垂直对齐。

div 内的一个单元格表格处理垂直对齐,并且向后兼容回到石器时代!

Just use a one-cell table inside the div! Just set the cell and table height and with to 100% and you can use the vertical-align.

A one-cell table inside the div handles the vertical-align and is backward compatible back to the Stone Age!

瀞厅☆埖开 2024-07-11 19:57:16

对我来说,它是这样工作的:

<div style="width:70px; height:68px; float:right; display: table-cell; line-height: 68px">
    <a href="javascript:void(0)" style="margin-left: 4px; line-height: 2" class="btn btn-primary">Login</a>
</div>

使用 Bootstrap 类将“a”元素转换为按钮,现在它在外部“div”内部垂直居中。

For me, it worked this way:

<div style="width:70px; height:68px; float:right; display: table-cell; line-height: 68px">
    <a href="javascript:void(0)" style="margin-left: 4px; line-height: 2" class="btn btn-primary">Login</a>
</div>

The "a" element converted to a button, using Bootstrap classes, and it is now vertically centered inside an outer "div".

×纯※雪 2024-07-11 19:57:16

这是我针对 div 内的 i 元素的个人解决方案。

JSFiddle 示例

HTML

<div class="circle">
    <i class="fa fa-plus icon">
</i></div>

CSS

.circle {
   border-radius: 50%;
   color: blue;
   background-color: red;
   height:100px;
   width:100px;
   text-align: center;
   line-height: 100px;
}

.icon {
  font-size: 50px;
  vertical-align: middle;
}

This is my personal solution for an i element inside a div.

JSFiddle Example

HTML

<div class="circle">
    <i class="fa fa-plus icon">
</i></div>

CSS

.circle {
   border-radius: 50%;
   color: blue;
   background-color: red;
   height:100px;
   width:100px;
   text-align: center;
   line-height: 100px;
}

.icon {
  font-size: 50px;
  vertical-align: middle;
}
━╋う一瞬間旳綻放 2024-07-11 19:57:16

我的技巧是在div内放一个表格,一行一列,宽度和高度设置为100%,属性vertical-align:middle:

<div>

    <table style="width:100%; height:100%;">
        <tr>
            <td style="vertical-align:middle;">
                BUTTON TEXT
            </td>
        </tr>
    </table>

</div>

Fiddle:
http://jsfiddle.net/joan16v/sbq​​jnn9q/

My trick is to put a table inside the div with one row and one column, set 100% of width and height, and the property vertical-align:middle:

<div>

    <table style="width:100%; height:100%;">
        <tr>
            <td style="vertical-align:middle;">
                BUTTON TEXT
            </td>
        </tr>
    </table>

</div>

Fiddle:
http://jsfiddle.net/joan16v/sbqjnn9q/

酒浓于脸红 2024-07-11 19:57:16

所有这些都需要在 div 内垂直对齐

如何对齐? 图像的顶部与文本的顶部对齐吗?

其中一张图像需要绝对定位在 div 内。

相对于 DIV 绝对定位? 也许你可以勾勒出你正在寻找的东西......?

fd 描述了绝对定位的步骤,以及调整 H1 元素的显示,使图像与其内联显示。 为此,我将补充一点,您可以使用 vertical-align 样式对齐图像:

#header h1 { display: inline; }
#header img { vertical-align: middle; }

...这会将标题和图像放在一起,并对齐顶部边缘。 存在其他对齐选项; 请参阅文档。 您可能还会发现删除 DIV 并将图像移动到 H1 元素内是有益的 - 这为容器提供了语义值,并且无需调整 H1 的显示代码>:

<h1 id=header">
   <img src=".." ></img>
   testing...
   <img src="..."></img>
</h1>

All of them need to be vertically aligned within the div

Aligned how? Tops of the images aligned with the top of the text?

One of the images needs to be absolute positioned within the div.

Absolutely positioned relative to the DIV? Perhaps you could sketch out what you're looking for...?

fd has described the steps for absolute positioning, as well as adjusting the display of the H1 element such that images will appear inline with it. To that, i'll add that you can align the images by use of the vertical-align style:

#header h1 { display: inline; }
#header img { vertical-align: middle; }

...this would put the header and images together, with top edges aligned. Other alignment options exist; see the documentation. You might also find it beneficial to drop the DIV and move the images inside the H1 element - this provides semantic value to the container, and removes the need to adjust the display of the H1:

<h1 id=header">
   <img src=".." ></img>
   testing...
   <img src="..."></img>
</h1>
箹锭⒈辈孓 2024-07-11 19:57:16

几乎所有方法都需要指定高度,但通常我们没有任何高度。

所以这里有一个 CSS 3 三行技巧,不需要知道高度。

.element {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

即使在 Internet Explorer 9 中也支持它。

及其供应商前缀:

.element {
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

来源:垂直只需 3 行 CSS 即可对齐任何内容

Almost all methods needs to specify the height, but often we don't have any heights.

So here is a CSS 3 three-line trick that doesn't require to know the height.

.element {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

It's supported even in Internet Explorer 9.

with its vendor prefixes:

.element {
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

Source: Vertical align anything with just 3 lines of CSS

月下客 2024-07-11 19:57:16

要将块元素定位到中心(适用于 Internet Explorer 9 及更高版本),需要包装器 div

.vcontainer {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
}

To position block elements to the center (works in Internet Explorer 9 and above), it needs a wrapper div:

.vcontainer {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
}
终陌 2024-07-11 19:57:16

使用这个公式,它将始终有效而不会出现裂缝:

#outer {height: 400px; overflow: hidden; position: relative;}
#outer[id] {display: table; position: static;}

#middle {position: absolute; top: 50%;} /* For explorer only*/
#middle[id] {display: table-cell; vertical-align: middle; width: 100%;}

#inner {position: relative; top: -50%} /* For explorer only */
/* Optional: #inner[id] {position: static;} */
<div id="outer">
  <div id="middle">
    <div id="inner">
      any text
      any height
      any content, for example generated from DB
      everything is vertically centered
    </div>
  </div>
</div>

Use this formula, and it will work always without cracks:

#outer {height: 400px; overflow: hidden; position: relative;}
#outer[id] {display: table; position: static;}

#middle {position: absolute; top: 50%;} /* For explorer only*/
#middle[id] {display: table-cell; vertical-align: middle; width: 100%;}

#inner {position: relative; top: -50%} /* For explorer only */
/* Optional: #inner[id] {position: static;} */
<div id="outer">
  <div id="middle">
    <div id="inner">
      any text
      any height
      any content, for example generated from DB
      everything is vertically centered
    </div>
  </div>
</div>

唐婉 2024-07-11 19:57:16

我朋友的一个技巧:

div:before {content:" "; display:inline-block; height:100%; vertical-align:middle;}
div p {display:inline-block;}
<div style="height:100px; border:1px solid;">
    <p style="border:1px dotted;">I'm vertically centered.</p>
</div>

演示此处

A technique from a friend of mine:

div:before {content:" "; display:inline-block; height:100%; vertical-align:middle;}
div p {display:inline-block;}
<div style="height:100px; border:1px solid;">
    <p style="border:1px dotted;">I'm vertically centered.</p>
</div>

Demo here.

千里故人稀 2024-07-11 19:57:16
 .outer {
   display: flex;
   align-items: center; 
   justify-content: center;
 }
 .outer {
   display: flex;
   align-items: center; 
   justify-content: center;
 }
苦笑流年记忆 2024-07-11 19:57:16

它对我有用:

.vcontainer {
    min-height: 10em;
    display: table-cell;
    vertical-align: middle;
}

It worked for me:

.vcontainer {
    min-height: 10em;
    display: table-cell;
    vertical-align: middle;
}
烟─花易冷 2024-07-11 19:57:16

垂直和水平对齐元素

使用其中之一。 结果是相同的:

  1. Bootstrap 4
  2. CSS3

在此处输入图像描述

1. Bootstrap 4.3+

对于垂直对齐:d-flexalign-items-center

对于水平对齐:d- flex justify-content-center

对于垂直和水平对齐:d-flexalign-items-center justify-content-center

.container {
    height: 180px;
    width:100%;
    background-color: blueviolet;
}

.container > div {
  background-color: white;
  padding: 1rem;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
rel="stylesheet"/>

<div class="d-flex align-items-center justify-content-center container">
  <div>I am in Center</div>
</div>

2.CSS3

.container {
    height: 180px;
    width:100%;
    background-color: blueviolet;
}

.container > div {
  background-color: white;
  padding: 1rem;
}

.center {
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="container center">
    <div>I am in Center</div>
</div>

Vertically and horizontally align element

Use either of these. The result would be the same:

  1. Bootstrap 4
  2. CSS3

Enter image description here

1. Bootstrap 4.3+

For vertical alignment: d-flex align-items-center

For horizontal alignment: d-flex justify-content-center

For vertical and horizontal alignment: d-flex align-items-center justify-content-center

.container {
    height: 180px;
    width:100%;
    background-color: blueviolet;
}

.container > div {
  background-color: white;
  padding: 1rem;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
rel="stylesheet"/>

<div class="d-flex align-items-center justify-content-center container">
  <div>I am in Center</div>
</div>

2. CSS 3

.container {
    height: 180px;
    width:100%;
    background-color: blueviolet;
}

.container > div {
  background-color: white;
  padding: 1rem;
}

.center {
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="container center">
    <div>I am in Center</div>
</div>

与君绝 2024-07-11 19:57:16

我使用了这个非常简单的代码:

div.ext-box { display: table; width:100%;}
div.int-box { display: table-cell; vertical-align: middle; }
<div class="ext-box">
    <div class="int-box">
        <h2>Some txt</h2>
        <p>bla bla bla</p>
    </div>
</div>

显然,无论您使用 .class 还是 #id,结果都不会改变。

I used this very simple code:

div.ext-box { display: table; width:100%;}
div.int-box { display: table-cell; vertical-align: middle; }
<div class="ext-box">
    <div class="int-box">
        <h2>Some txt</h2>
        <p>bla bla bla</p>
    </div>
</div>

Obviously, whether you use a .class or an #id, the result won't change.

素食主义者 2024-07-11 19:57:16

现在 Flexbox 支持不断增加,应用于包含元素的 CSS 将垂直居中所有包含的项目(除了那些本身指定对齐方式的项目,例如 align-self:start)

.container {
    display: flex;
    align-items: center;
}

如果您还需要定位 Internet Explorer 10 及更早版本 (<4.4 (KitKat)) Android 浏览器:

.container {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;
    align-items: center;
}

Now that Flexbox support is increasing, this CSS applied to the containing element would vertically center all contained items (except for those items that specify the alignment themselves, e.g. align-self:start)

.container {
    display: flex;
    align-items: center;
}

Use the prefixed version if you also need to target Internet Explorer 10, and older (< 4.4 (KitKat)) Android browsers:

.container {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;
    align-items: center;
}
煮茶煮酒煮时光 2024-07-11 19:57:16

哇,这个问题很流行。 它基于对 vertical-align 属性的误解。 这篇优秀的文章对此进行了解释:

了解vertical-align,或“如何(不是)垂直居中内容” 作者:Gavin Kistner。

“如何在 CSS 中居中” 是一个很棒的网络工具,可以帮助找到必要的 CSS针对不同情况的居中属性。


简而言之(并防止链接失效)

  • 内联元素(并且内联元素)可以是垂直的通过vertical-align: middle在上下文中对齐。 然而,“上下文”并不是整个父容器的高度,而是它们所在文本行的高度。 jsfiddle示例
  • 对于块元素,垂直对齐比较困难,很大程度上取决于具体情况:
    • 如果内部元素可以有固定高度,您可以将其位置绝对并指定其高度边距-顶部和顶部位置。 jsfiddle 示例
    • 如果居中元素由单行组成并且其父高度是固定的,您只需设置容器的line- height 来填充其高度。 根据我的经验,这种方法非常通用。 jsfiddle 示例
    • ……这样的特殊情况还有很多。


Wow, this problem is popular. It's based on a misunderstanding in the vertical-align property. This excellent article explains it:

Understanding vertical-align, or "How (Not) To Vertically Center Content" by Gavin Kistner.

“How to center in CSS” is a great web tool which helps to find the necessary CSS centering attributes for different situations.


In a nutshell (and to prevent link rot):

  • Inline elements (and only inline elements) can be vertically aligned in their context via vertical-align: middle. However, the “context” isn’t the whole parent container height, it’s the height of the text line they’re in. jsfiddle example
  • For block elements, vertical alignment is harder and strongly depends on the specific situation:
    • If the inner element can have a fixed height, you can make its position absolute and specify its height, margin-top and top position. jsfiddle example
    • If the centered element consists of a single line and its parent height is fixed you can simply set the container’s line-height to fill its height. This method is quite versatile in my experience. jsfiddle example
    • … there are more such special cases.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文