div에서 요소를 세로로 정렬하는 방법은 무엇입니까?


792

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

이미지 중 하나를 absolutediv 내에 배치 해야합니다 .

모든 공통 브라우저에서 작동하려면 CSS가 무엇입니까?

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

14
: 나는 수직 align..I 모든 방법의 목록은 여기를 떠나려고했다 jsfiddle.net/techsin/FAwku/1
— 무하마드 Umer

2
다음은 두 개의 수평, 수직, 사업부 내에서 요소를 중심 간단한 방법이나 모두 (순수 CSS)이다 stackoverflow.com/a/31977476/3597276
— 마이클 벤자민

1
margin-top : auto 및 margin-bottom : auto (많은 경우에 적용).
— CrippledTable

답변:


932

와우,이 문제는 인기가 있습니다. vertical-align재산 에 대한 오해에 근거하고 있습니다. 이 훌륭한 기사는 다음과 같이 설명합니다.

vertical-alignGavin Kistner의 "콘텐츠를 세로로 가운데 정렬 하는 방법" 이해

“CSS를 중심에 두는 방법” 은 다양한 상황에 필요한 CSS 중심 속성을 찾는 데 도움이되는 훌륭한 웹 도구입니다.


간단히 말해서 (그리고 링크 썩음 방지) :

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

142
"유효하지 않은"솔루션의 문제점 vertical-align: middle은 고정 된 높이를 지정해야한다는 것입니다. 반응 형 웹 디자인 에는 그다지 불가능합니다 .
— Emilie

1
<div height = "## px"> 내 텍스트 </ div> div height 속성에 사용 된 것과 동일한 값을 사용하여 lineHeight 속성을 설정했습니다. '## px'(##이 값 때문에 내 경우에는 역동적 임) 감사합니다
— patricK

8
이것은 또한 작동 inline-block및 table-cell요소. 이와 관련하여 문제가 line-height있는 경우 컨테이너 요소 (예 : 컨텍스트)가 vertical-align라인 상자 계산에 사용되므로 조정하십시오 .
— Alex W

1
css-tricks.com/centering-css-complete-guide <-여기에 제시된 몇 가지 좋은 옵션은 대부분 테이블 / 테이블 셀 솔루션에 의지하는 것으로 나타났습니다.
— shaunhusain

1
은 박스 오른쪽 밖으로 근무하기 때문에이 도구는 (howtocenterincsss.com) 꽤 굉장 내부에 기존 CSS! 슈퍼 레어입니다. 예를 들어 HTML에서 스타일 시트 전체를 복사해야했던 시절을 기억하고 필요할 때까지 요소를 하나씩 차례로 제거하고 이름을 바꿉니다. 이 사이트에는 해당되지 않습니다!
— konstantin

190

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

좋은 해결책입니다. 감사합니다. 내부 요소가 컨테이너보다 큰 경우 flexbox 표시를 가로 스크롤 막대로 만드는 방법을 제안 할 수 있습니까? (파워 포인트의 캔버스와 같이 컨테이너 내에서 내부 요소를 확대 / 축소 할 수있게하려고합니까?) 전혀 가능합니까?
— Boris Burkov 5

1
@YazidErman이 솔루션은 flexbox에 의존하므로 IE 10 이상 만 지원하거나 다른 최신 브라우저 caniuse.com/#search=flexbox Flexbox는 지원되는 곳은 훌륭하지만 어디에나있는 것은 아닙니다. 디스플레이 테이블과 테이블 셀은 아마도 가장 좋은 솔루션 일 것입니다. 컨테이너는 테이블 일 필요가 있습니다. 중심 요소는 디스플레이 테이블 셀로 요소를 감싸고 여기에 다른 답변이 지적한 것처럼 가운데에 놓일 수 있습니다.
— shaunhusain

1
왜 이렇게 찾기 힘들었습니까?>. <답변 주셔서 감사합니다! 다른 답변이 작동하지 않는 시나리오에서 이것이 효과가 있음을 확인할 수 있습니다.
— 마이클 맥 케나

1
flexbox의 유용한 CSS 트릭 가이드 다음 align-items섹션을보십시오
— icc97

1
2020 년에는 flexbox caniuse.com/#feat=flexbox
— tonygatta

116

이 매우 간단한 코드를 사용했습니다.

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, 결과는 변경되지 않습니다.


3
다음은 9 가지 정렬 가능성 (전체 가운데 하단 및 왼쪽 가운데 오른쪽)에 대한 전체 예입니다. jsfiddle.net/webMac/0swk9hk5
— webMac

2020 년에는 flexbox caniuse.com/#feat=flexbox
— tonygatta

나를 위해 완벽하게 작동
— huynq0911

49

그것은 나를 위해 일했다 :

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

9
더 이상 "블록"요소가 아닌가?
— Pacerier

7
그러면 가로 정렬을 원한다면margin : 0 autodisplay: table-cell
— Ortomala Lokni

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

7
이 솔루션이 가장 빠르고 이해하기 쉽다고 생각합니다. 아마도 내가 선택한 답변을 이해하기에 인내하지 않았기 때문일 것입니다. Flexbox의 모든 것!
— modulitos

1
의 추가는 justify-content: center수평 중심의 나의 부족을 고정
— 사무엘 슬레이드에게

22

내 친구의 기술 :

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

여기 데모


1
이 기술은 여기에 더 자세히 설명되어 있습니다 : css-tricks.com/centering-in-the-unknown
— nerdess

18

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

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

2
이 방법을 사용하면 요소가 "반 픽셀"에 배치되어 요소가 흐려질 수 있습니다. 이에 대한 해결책은 요소의 관점을 설정하는 것입니다. 변환 : 원근법 (1px) translateY (-50 %);
— Simon

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>

15

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

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


2
CSS에서 이런 종류의 선택기 "#outer [id]"를 본 적이 없습니다. 어떻게해야합니까? 아이디 대신 수업을 받으면 어떻게 되나요?
— Alexa Adrian

12

거의 모든 방법은 높이를 지정해야하지만 종종 높이가 없습니다.
여기에 높이를 알 필요가없는 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://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/


그러나 이것은 요소의 부모 높이가 고정 된 경우에만 작동하는 것 같습니다. 백분율 값을 가진 'top'속성은 고정 높이를 가진 컨테이너에서만 작동합니다. 맞습니까?
— ucdream

예, 일부 경우에만 작동합니다. 나중에이 방법으로 문제가 발생했습니다. 가능한 한 최대한 많은 가능성을 가지고 있어야합니다. 모든 방법이 있기 때문에 좋은 방법을 얻을 때까지 모든 것을 테스트해야합니다. 특정한 경우에는 작동하지 않는 것들이 있습니다 ...
— Shadoweb

12

두 가지 방법으로 요소를 세로 및 가로로 정렬 할 수 있습니다

  1. 부트 스트랩 4
  2. CSS3

여기에 이미지 설명을 입력하십시오

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;  // verticall center
    justify-content: center; // horizontally 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>


1
Bootstrap은 클래스에서 동일한 flex 속성을 사용하기 때문에 두 가지 방법은 기본적으로 동일합니다.
— Mx.

부트 스트랩은 마술이 아닙니다. 모든 사람에게 영향을 미치는 CSS 제한 사항이 동일합니다. 평균에서 수행하는 작업을 숨기고 있습니다. 사용자.
— JasonGenX

10

내 속임수는 div 안에 1 행 1 열의 테이블을 넣고 너비와 높이를 100 % 설정하고 속성을 vertical-align : middle로 설정하는 것입니다.

<div>

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

</div>

피들 : http://jsfiddle.net/joan16v/sbqjnn9q/


7
이것은 많은 헤드 스크래치를 피하는 가장 좋은 방법으로 보입니다. 왜 CSS에 수직 정렬 표준이 없는지에 대해서는 여전히 혼란 스럽습니다.
— Kokodoko

5

부모 div에서 센터 자식 div를 만드는 3 가지 방법

  • 절대 위치 결정 방법
  • Flexbox 방법
  • 변환 / 번역 방법

    여기에 이미지 설명을 입력하십시오

    데모

/* 1st way */
.parent1 {
  background: darkcyan;
   width: 200px;
   height: 200px;
   position: relative;
}
.child1 {
  background: white;
  height: 30px;
  width: 30px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -15px;
}

/* 2nd way */
.parent2 {
  display: flex;
  justify-content: center;
  align-items: center;
  background: darkcyan;
  height: 200px;
  width: 200px;
}
.child2 {
  background: white;
  height: 30px;
  width: 30px;
}

/* 3rd way */
.parent3 {
  position: relative;
  height: 200px;
  width: 200px;
  background: darkcyan;
}
.child3 {
  background: white;
  height: 30px;
  width: 30px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<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>


4

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/


3

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

이를 방지하기 위해 h1을 인라인 흐름 동작을 갖도록 설정할 수 있습니다.

#header > h1 { display: inline; }

div 안에 img를 절대적으로 배치하려면 제대로 작동하기 전에 포함 div를 "알려진 크기"로 설정해야합니다. 내 경험상, 당신은 또한 position 속성을 default-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>

4
DOCTYPE을 올바르게 설정하면 특히 Internet Explorer에서 CSS가 렌더링되는 방식에 큰 차이가 생길 수 있습니다. 브라우저간에보다 일관된 동작을 기대할 수 있도록 엄격한 표준 모드와 일치하는 것으로 알려진 DOCTYPE을 선택하는 것이 좋습니다.
— Mike Tunnicliffe

2
/ : 난 단지 방법이 있는지 테스트하는 것입니다 .. 브라우저 사이에 일관성을 '기대'없는 것
— Cocowalla

3

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 함수는 이전 브라우저와의 호환성에 대해 테스트되지 않았습니다.


3

오늘과 같이 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%;
}

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


매우 깨끗한 솔루션. 이것은 나를 위해 잘 작동했습니다.
— Akalonda 2018 년

2

내가 가장 좋아하는 방법은 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>


1

div 안에 하나의 셀 테이블을 사용하십시오! 셀과 테이블 높이를 100 %로 설정하면 세로 정렬을 사용할 수 있습니다.

div 내부의 1 셀 테이블은 수직 정렬을 처리하고 석기 시대와 역 호환됩니다!


0

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>

0

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

0

나를 위해 다음과 같이 작동했습니다.

<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"내부에서 세로로 가운데에 배치됩니다.


0

디스플레이 플렉스를 사용하려면 먼저 정렬하려는 항목의 컨테이너를 포장해야합니다.

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

그런 다음 예제에서 래퍼 div 또는 outdiv에 다음 CSS를 적용하십시오.

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

코드 만 답변하지 않는 것이 좋습니다. 이것이 어떻게 문제를 해결하는지 또는 이것이 기존 답변과 어떻게 다른지에 대한 설명을 추가하십시오. 리뷰에서
— Nick

-3

딱 이것:

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


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

-4

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

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/


-4

나는 웹 프로그래밍에 들어간 .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>

7
새로운 웹 개발자에게 잘못된 일을하는 방법, HTML은 콘텐츠 정의, CSS는 HTML 스타일링, JavaScript는 런타임에 조건에 따라 두 가지를 모두 조작하는 방법을 가르치고 있습니다. 이들을 혼합하면 스파게티와 성능 집약적 코드로 빠르게 이어질 수 있습니다.
— OverCoder

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

...

또는 CSS

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

브라우저 범위


1
div가 표시되어 있기 때문에 세로 정렬 속성이 적용되지 않습니다. 기본적으로 블록이며 변경을 위해 아무것도 수행되지 않은 것으로 보입니다.
— Quentin

3
분명히 디스플레이가 업데이트되었습니다 table-cell수있는 vertical-align: middle;일을. 더 나은, 그것은 중첩 된 래퍼 / 버퍼 DIV 필요없이 작동하고, 그것은 텍스트와 이미지 (또는 둘 다) 모두를 위해 작동 하고 당신은 위치 속성을 변경할 필요가 없습니다.
— MSpreij 2016 년

3
이것은 작동합니다. 세로 정렬 속성을 사용하는 표 셀로 표시를 변경합니다. 사람들이 왜이 투표를했는지 모르겠다.
— texasbruce

1
예, 내가 아는 한 이것은 div에서 세로로 중심을 잡는 가장 방해가되지 않는 방법입니다. +1
— Pma

그래, 어쩌면 내가 표시 추가 ... 너무 빨리 내 결론이었다 : 테이블 셀 breakes 사업부 마진과 additionaly 경계 외부 DIV를 표시, 국경 경계 반경 표시와 함께 외부의 사업부의 istead의 내부에 둥근 모서리
— PMA
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.