문제

두 개의 이미지가 포함된 div가 있고 h1.이들 모두는 div 내에서 서로 옆에 수직으로 정렬되어야 합니다.

이미지 중 하나는 다음과 같아야 합니다. absolute div 내에 위치합니다.

이것이 모든 일반 브라우저에서 작동하려면 CSS가 무엇입니까?

<div id="header">
    <img src=".." ></img>
    <h1>testing...</h1>
    <img src="..."></img>
</div>
도움이 되었습니까?

해결책

와, 이 문제가 인기가 많네요.이는 에 대한 오해에 근거한 것입니다. vertical-align 재산.이 훌륭한 기사에서는 다음과 같이 설명합니다.

이해 vertical-align, 또는 "콘텐츠를 수직으로 가운데에 맞추는 방법" 개빈 키스트너 지음.

"CSS에서 중앙에 배치하는 방법" 다양한 상황에 필요한 CSS 중심 속성을 찾는 데 도움이 되는 훌륭한 웹 도구입니다.


간단히 말해서 (그리고 링크 부패를 방지하기 위해):

  • 인라인 요소 (그리고 오직 인라인 요소)는 다음을 통해 해당 컨텍스트에서 수직으로 정렬될 수 있습니다. vertical-align: middle.그러나 "컨텍스트"는 전체 상위 컨테이너 높이가 아니라 해당 컨테이너가 있는 텍스트 줄의 높이입니다. jsfiddle 예
  • 블록 요소의 경우 수직 정렬이 더 어렵고 특정 상황에 따라 크게 달라집니다.
    • 내부 요소가 고정 높이, 당신은 그 위치를 만들 수 있습니다 absolute 그리고 그것을 지정 height, margin-top 그리고 top 위치. jsfiddle 예
    • 중앙에 있는 요소인 경우 한 줄로 구성되어 있다 그리고 부모 높이는 고정되어 있습니다. 간단히 컨테이너의 line-height 높이를 채우기 위해.이 방법은 내 경험상 매우 다양합니다. jsfiddle 예
    • …그런 특별한 경우가 더 있습니다.

다른 팁

이제 Flexbox 지원이 증가하고 있으므로 포함 요소에 적용된 이 CSS는 포함된 항목을 수직으로 가운데에 배치합니다.

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

Explorer 10 및 이전(< 4.4) 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;
}

저는 다음과 같은 매우 간단한 코드를 사용했습니다.

HTML:

<div class="ext-box">
    <div class="int-box">
        <h2>Some txt</h2>
        <p>bla bla bla</p>
    </div>
</div>

CSS:

div.ext-box { display: table; width:100%;}
div.int-box { display: table-cell; vertical-align: middle; }

분명히, 당신이 .class 또는 #id, 결과는 변경되지 않습니다.

그것은 나를 위해 일했습니다 :

.vcontainer {
    min-height: 10em;
    display: table-cell;
    vertical-align: middle;
}
 .outer {
   display: flex;
   align-items: center; 
   justify-content: center;
 }

내 친구의 기술:

HTML:

<div style="height:100px; border:1px solid;">
    <p style="border:1px dotted;">I'm vertically centered.</p>
</div>

CSS:

div:before {content:" "; display:inline-block; height:100%; vertical-align:middle;}
div p {display:inline-block;}

데모 여기

모두 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>

블록 요소를 중앙에 배치하려면(IE9 이상에서 작동) 래퍼가 필요합니다. div:

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

이 공식을 사용하면 항상 균열 없이 작동합니다.

#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>

거의 모든 메소드는 높이를 지정해야 하지만 높이가 없는 경우가 많습니다.
여기에 높이를 알 필요가 없는 CSS3 3줄 트릭이 있습니다.

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

IE9에서도 지원됩니다.

공급업체 접두사:

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

원천: http://zerosix three.se/vertical-align-anything-with-just-3-lines-of-css/

내 비결은 div 내부에 1행과 1열이 있는 테이블을 넣고 너비와 높이를 100%로 설정하고 수직 정렬:중간 속성을 설정하는 것입니다.

<div>

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

</div>

깡깡이:http://jsfiddle.net/joan16v/sbqjnn9q/

기본적으로 h1은 블록 요소이며 첫 번째 img 다음 줄에 렌더링되고 두 번째 img가 블록 다음 줄에 표시됩니다.

이 문제가 발생하지 않도록 하려면 h1이 인라인 흐름 동작을 갖도록 설정할 수 있습니다.

#header > h1 { display: inline; }

img의 위치를 ​​절대적으로 지정하는 경우 div 내부, 이것이 제대로 작동하려면 먼저 포함 div가 "알려진 크기"를 갖도록 설정해야 합니다.내 경험에 따르면 위치 속성도 기본 위치에서 변경해야 합니다.나에게 맞는 상대 작품:

#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>

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

결과

Result

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

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 height 그리고 width 또한.

메모:calc 기능은 이전 브라우저와의 호환성 테스트를 거치지 않았습니다.

오늘로서 저는 CSS3를 사용하여 div에서 여러 텍스트 줄을 수직으로 정렬하는 새로운 해결 방법을 찾았습니다(그리고 UI를 아름답게 하기 위해 부트스트랩 v3 그리드 시스템도 사용하고 있습니다). 이는 아래와 같습니다.

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

내 이해에 따르면 요소를 포함하는 텍스트의 직계 부모에는 높이가 있어야 합니다.나는 그것이 당신에게도 도움이되기를 바랍니다.감사해요!

요소를 수직 및 수평으로 정렬하는 방법에는 두 가지가 있습니다.

enter image description here

1.부트스트랩 4.3.X

수직 정렬의 경우: d-flex align-items-center

수평 정렬의 경우: d-flex justify-content-center

.container {
    height: 180px;
    width:100%;
}
<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 bg-info container">
  <div class="bg-light p-2">I am in Center</div>
</div>

2.CSS3

.container {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #17a2b8;
    height: 180px;
    width:100%;
}

.child {
  background-color: #f8f9fa;
  padding: 0.5rem;
}
<div class="container">
  <div class="child">I am in Center</div>
</div>

div 내부에 단일 셀 테이블을 사용하세요!셀과 테이블 높이를 100%로 설정하면 수직 정렬을 사용할 수 있습니다.

div 내부의 단일 셀 테이블은 수직 정렬을 처리하며 석기 시대까지 역호환됩니다!

나는 1년 넘게 다음 솔루션(위치 지정 및 줄 높이 없음)을 사용해 왔으며 IE 7 및 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>

이것은 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;
}

나에게는 다음과 같은 방식으로 작동했습니다.

<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>

"a" 요소는 Bootstrap 클래스를 사용하여 버튼으로 변환되었으며 이제 외부 "div" 내부의 수직 중앙에 배치됩니다.

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


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

딱 이것:

<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 내부의 단일 셀 테이블은 수직 정렬을 처리하며 석기 시대까지 역호환됩니다!

<!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>

다음은 또 다른 (반응형) 접근 방식입니다.

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/

저는 이제 막 웹 프로그래밍에 입문한 .NET 사용자입니다.저는 CSS를 사용하지 않았습니다(음, 약간).나는 jQuery의 .css 함수와 함께 수직 중심화를 달성하기 위해 약간의 JavaScript를 사용했습니다.

그냥 테스트의 모든 내용을 게시하고 있습니다.아마도 지나치게 우아하지는 않지만 지금까지는 작동합니다.

script.

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

        <script type="application/javascript">
            function centerElementVertically(id) {
                var btnDivHeight = $(id).outerHeight();
                var prnt = $(id).parent();
                var parentHeight = prnt.outerHeight();

                var newTop = ((parentHeight - btnDivHeight) / 2) + 'px';
                var newPct = newTop / parentHeight+'%;';

                $(id).css({top: newTop});
            }

            function showAlert(){
                alert("alert");
            }

            $(window).load(()=>{
                centerElementVertically('#buttonRight');
                centerElementVertically('#buttonLeft');
                centerElementVertically('#testerbtn')
            });

            $(window).resize(()=>{
                centerElementVertically('#buttonRight');
                centerElementVertically('#buttonLeft');
                centerElementVertically('#testerbtn')
            })
        </script>

        <style>
            #div1 {
                position:relative;
                height: 33%;
                background-color: red;
                overflow: hidden;
            }
            #buttonLeft {
                position: relative;
                float:left;
                width:50%;
                height:20%;
                background-color: cornsilk;
            }
            #buttonRight {
                position: relative;
                float:right;
                width:50%;
                height:50%;
                background-color: darkorchid;
            }
            #testerbtn {
                position: absolute;
            }
            body {
                background-color: aqua;
            }
        </style>

        <body>
            <div id="div1">
                <div id="buttonLeft">
                    <button id="testerbtn">tester</button>
                </div>
                <div id="buttonRight"></div>
            </div>
        </body>
    </head>
</html>
<div id="header" style="display: table-cell; vertical-align:middle;">

...

또는 CSS

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

브라우저 범위

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top