수평 및 수직 요소를 중심에 배치하는 방법


408

탭 내용을 세로로 가운데에 맞추려고하지만 CSS 스타일을 추가 display:inline-flex하면 가로 텍스트 정렬이 사라집니다.

각 탭에 대해 텍스트 맞춤 x 및 y를 어떻게 만들 수 있습니까?

* { box-sizing: border-box; }
#leftFrame {
  background-color: green;
  position: absolute;
  left: 0;
  right: 60%;
  top: 0;
  bottom: 0;
}
#leftFrame #tabs {
  background-color: red;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 25%;
}
#leftFrame #tabs div {
  border: 2px solid black;
  position: static;
  float: left;
  width: 50%;
  height: 100%;
  text-align: center;
  display: inline-flex;
  align-items: center;
}
<div id=leftFrame>
  <div id=tabs>
    <div>first</div>
    <div>second</div>
  </div>
</div>


CSS 유형 만 사용하여 가로 및 세로 중심 div없이 표시 유형 flex 및 CSS 2D 변환을 사용하는 최신 CSS 메소드 freakyjolly.com/…
— Code Spy

답변:


666
  • 접근법 1- transform translateX/ translateY:

    여기 예 / 전체 화면 예

    에서 지원되는 브라우저 (대부분), 당신은 사용할 수 있습니다 top: 50%/ left: 50%와 함께 translateX(-50%) translateY(-50%)수평 요소를 중심 / 동적 수직으로.

.container {
    position: absolute;
    top: 50%;
    left: 50%;
    -moz-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
}
<div class="container">
    <span>I'm vertically/horizontally centered!</span>
</div>


  • 접근법 2-Flexbox 방법 :

    여기 예 / 전체 화면 예

    에서 지원되는 브라우저 의 설정 display대상에 요소의 flex사용을 align-items: center수직 중심과 justify-content: center수평 중심에 대해. 추가 브라우저 지원을 위해 공급 업체 접두사를 추가하는 것을 잊지 마십시오 ( 예 참조 ).

html, body, .container {
    height: 100%;
}

.container {
    display: -webkit-flexbox;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-flex-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;
    justify-content: center;
}
<div class="container"> 
  <span>I'm vertically/horizontally centered!</span>
</div>


  • 접근법 3- table-cell/ vertical-align: middle:

    여기 예 / 전체 화면 예

    경우에 따라 html/ body요소의 높이가로 설정되어 있는지 확인해야합니다 100%.

    수직 정렬의 경우 부모 요소의 width/ height를 설정 100%하고 추가하십시오 display: table. 그런 다음 자식 요소를 들어, 변경 display에 table-cell추가합니다 vertical-align: middle.

    가로 text-align: center로 가운데를 맞추려면 텍스트와 다른 inline자식 요소 를 가운데에 추가 할 수 있습니다 . 또는 margin: 0 auto요소가 block수평 이라고 가정 하면을 사용할 수 있습니다 .

html, body {
    height: 100%;
}
.parent {
    width: 100%;
    height: 100%;
    display: table;
    text-align: center;
}
.parent > .child {
    display: table-cell;
    vertical-align: middle;
}
<section class="parent">
    <div class="child">I'm vertically/horizontally centered!</div>
</section>


  • 접근법 4- 50%변위를 통해 상단에서 절대 위치 :

    여기 예 / 전체 화면 예

    이 방법에서는 텍스트의 높이가 알려진 것으로 가정합니다 18px. 50%부모 요소를 기준으로 요소 를 맨 위에서 절대적으로 배치하십시오 . margin-top알려진 경우 높이의 절반 인 음수 값을 사용하십시오 ( 이 경우-) -9px.

html, body, .container {
    height: 100%;
}

.container {
    position: relative;
    text-align: center;
}

.container > p {
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    margin-top: -9px;
}
<div class="container">
    <p>I'm vertically/horizontally centered!</p>
</div>


  • 접근법 5- line-height방법 (최소 유연성 – 제안되지 않음) :

    여기 예

    경우에 따라 상위 요소의 높이가 고정됩니다. 수직 센터링의 line-height경우 자식 요소의 값을 부모 요소의 고정 높이와 동일하게 설정하면 됩니다.

    -이 솔루션은 어떤 경우에 작동하지만, 그것의 가치는 여러 줄의 텍스트가있는 경우는 작동하지 않습니다 지적 과 같습니다 .

.parent {
    height: 200px;
    width: 400px;
    background: lightgray;
    text-align: center;
}

.parent > .child {
    line-height: 200px;
}
<div class="parent">
    <span class="child">I'm vertically/horizontally centered!</span>
</div>


3
그렇습니다. 나는 이미 CSS3에서 인라인 플렉스를 사용 했으므로이 aproach를 올바르게 취하는 방법을 완전히 잊어 버렸습니다. 정말 고맙습니다. 대단히 감사합니다.
— shuji

위의 "전체 화면"예제를 모두 열었습니다. 세로 정렬이 항상 화면 하단 근처에서 약간 너무 높은 것을 확인했습니다 (해상도 1920x1080, 레이블이 화면에서 20 픽셀로 너무 낮음). 내 웹 페이지에서 접근법 # 2를 구현했으며 div가 전체 화면이 아니더라도 동일한 문제가 발생했습니다. 내 웹 페이지에서 문제가 더욱 악화됩니다. (100px too low) ...
— AXMIM

flexbox (IE9 +, [90 % + browser market coverage] (caniuse.com/#feat=flexbox)에서 작동) : display: flex부모와 align-self: center자식을 사용하여 Approach 6을 추가 할 수 있습니다 .
— Dan Dascalescu

나는 약간의 접근법 2 : jsfiddle.net/yeaqrh48/278을 변경했습니다 . 결과적으로 창의 높이를 줄이면 텍스트가 범위를 넘어서서 볼 수 없게됩니다. 이 문제를 해결하는 방법?
— ollazarev

1
@ josh-crozier 방금 css xd에 게시물 링크가있는 웹 사이트를 찾았습니다
— zoran404

31

CSS3이 옵션이거나 폴 백인 경우 transform을 사용할 수 있습니다.

.center {
    right: 50%;
    bottom: 50%;
    transform: translate(50%,50%);
    position: absolute;
}

위의 첫 번째 접근 방식과 달리 IE9 +에는 오버플로 버그가 있기 때문에 음수 변환에 left : 50 %를 사용하고 싶지 않습니다. 양의 올바른 값을 사용하면 가로 스크롤 막대가 표시되지 않습니다.


transform: translateX(50%) translateY(50%);대신 변형이되어야한다고 생각합니다 . 위의 변환은 Mozilla 변환 문서 에 따라 구문 상 올바르지 않습니다 .
— Eirik H

1
@EirikH 당신이 무엇을보고 있었는지 확실하지 않지만, 그 구문은 괜찮습니다 (그리고 문서에서 그렇게 말합니다). 의 대부분의 transform값 수 는 X와 Y 값을 단지 하나를 수행하기 위해 모두와 전문 기능을 수행 할 수있는 기본 기능이있다.
— Scott Marcus

9

상자를 세로 및 가로로 가운데 정렬하는 가장 좋은 방법은 두 개의 컨테이너를 사용하는 것입니다.

외부 컨테이너 :

  • 있어야한다 display: table;

내부 컨테이너 :

  • 있어야한다 display: table-cell;
  • 있어야한다 vertical-align: middle;
  • 있어야한다 text-align: center;

내용 상자 :

  • 있어야한다 display: inline-block;
  • 텍스트를 중앙에 배치하지 않으려면 가로 텍스트 정렬을 조정해야합니다.

데모 :

body {
    margin : 0;
}

.outer-container {
    display: table;
    width: 80%;
    height: 120px;
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        Center this!
     </div>
   </div>
</div>

이 바이올린을 참조하십시오 !

페이지 중앙을 중심으로 :

콘텐츠를 페이지 중앙에 배치하려면 외부 컨테이너에 다음을 추가하십시오.

  • position : absolute;
  • width: 100%;
  • height: 100%;

이에 대한 데모는 다음과 같습니다.

body {
    margin : 0;
}

.outer-container {
    position : absolute;
    display: table;
    width: 100%;
    height: 100%;
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        Center this!
     </div>
   </div>
</div>

이 바이올린을 참조하십시오 !


7

다음은 2 개의 간단한 flex 속성을 사용 하여 2 개의 축에서 n div 를 가운데 에 배치하는 방법입니다.

  • 컨테이너의 높이를 설정하십시오. 여기서 본체는 100vh 이상으로 설정되어 있습니다.
  • align-items: center 수직으로 블록을 중앙에 배치합니다
  • justify-content: space-around div 주위에 빈 공간을 분배합니다

body {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: space-around;
}
<div>foo</div>
<div>bar</div>


5

이 코드 스 니펫을 실행하면 세로 및 가로로 정렬 된 div가 표시됩니다.

html,
body,
.container {
  height: 100%;
  width: 100%;
}
.container {
  display: flex;
  align-items: center;
  justify-content: center;
}
.mydiv {
  width: 80px;
}
<div class="container">
  <div class="mydiv">h & v aligned</div>
</div>


3

가장 간단하고 깨끗한 솔루션은 CSS3 속성 "transform"을 사용하는 것입니다.

.container {
  position: relative;
}

.container a {
  position: absolute;
  top: 50%;
  transform: translate(0,-50%);
}
<div class="container">
  <a href="#">Hello world!</a>
</div>


3

    .align {
        display: flex;
        width: 400px;
        height: 400px;
        border: solid 1px black;
        align-items: center;
        justify-content: space-around;
    }
    .align div:first-child {
        width: 20px;
        height: 20px;
        background-color: red;
        position: absolute; 
    }
    .align div {
        width: 20px;
        height: 20px;
        background-color: blue;
    }
    <div class='align'>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </div>

첫 번째 아이는 중앙에서 수직 및 수평으로 정렬됩니다


2

Div를 페이지 중앙에 배치 check the fiddle link

#vh {
    border-radius: 15px;
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.4);
    padding: 25px;
    width: 200px;
    height: 200px;
    background: white;
    text-align: center;
    margin: auto;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}
<div id="vh">Div to be aligned vertically</div>

다른 옵션 업데이트 는 플렉스 박스를 사용하는 것입니다 check the fiddle link

.vh {
    background-color: #ddd;
    height: 200px;
    align-items: center;
    display: flex;
}
.vh > div {
    width: 100%;
    text-align: center;
    vertical-align: middle;
}
<div class="vh">
    <div>Div to be aligned vertically</div>
</div>


2

아래는 원하는 결과를 얻는 Flex-box 방식입니다

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Flex-box approach</title>
<style>
  .tabs{
    display: -webkit-flex;
    display: flex;
    width: 500px;
    height: 250px;
    background-color: grey;
    margin: 0 auto;
    
  }
  .f{
    width: 200px;
    height: 200px;
    margin: 20px;
    background-color: yellow;
    margin: 0 auto;
    display: inline; /*for vertically aligning */
    top: 9%;         /*for vertically aligning */
    position: relative; /*for vertically aligning */
  }
</style>
</head>
<body>

    <div class="tabs">
        <div class="f">first</div>
        <div class="f">second</div>        
    </div>

</body>
</html>


2

또 다른 방법은 테이블을 사용하는 것입니다.

<div style="border:2px solid #8AC007; height:200px; width:200px;">
  <table style="width:100%; height:100%">
    <tr style="height:100%">
      <td style="height:100%; text-align:center">hello, multiple lines here, this is super long, and that is awesome, dude</td>
    </tr>
  </table>
</div>


2

요소를 세로 및 가로로 가운데 맞추기 위해 아래 언급 된 속성을 사용할 수도 있습니다.

이 CSS 속성 은 항목을 정렬합니다 은 세로로 하고 다음 값을 허용합니다.

flex-start : 컨테이너 상단에 항목이 정렬됩니다.

flex-end : 컨테이너 바닥에 품목이 정렬됩니다.

가운데 : 컨테이너의 세로 가운데에 항목이 정렬됩니다.

baseline : 컨테이너의 기준선에 항목이 표시됩니다.

stretch : 컨테이너에 맞게 항목이 늘어 납니다 .

이 CSS 속성 justify-content 는 항목을 가로로 정렬하고 다음 값을 허용합니다.

플렉스 스타트 : 항목이 컨테이너의 왼쪽에 정렬됩니다.

플렉스 엔드 : 항목이 컨테이너의 오른쪽에 정렬됩니다.

센터 : 컨테이너의 가운데에 항목이 정렬됩니다.

공백 사이 : 항목이 같은 간격으로 표시됩니다.

space-around : 같은 간격으로 항목이 표시됩니다.


2

그리드 CSS 접근

#wrapper {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(3, 1fr);
}
.main {
    background-color: #444;
}
<div id="wrapper">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box main"></div>
</div>


2

다음 따라야 할 새로운 및 쉬운 솔루션 :

  .centered-class {
      align-items: center;
      display: flex;
      justify-content: center;
      width: 100vw;
      height: 100vh;
    }
<div class="centered-class">
  I'm in center vertically and horizontally.
</div>


1
  • 접근법 6

/*Change units to "%", "px" or whatever*/

#wrapper{
  width: 50%;
  height: 70vh;
  background: rgba(0,0,0,.5);
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
}
#left{
  width: 50%;
  height: 50vh;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  background: red;
}
#right{
  width: 50%;
  height: 50vh;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  margin: auto;
  background: green;
}
.txt{
  text-align: center;
  line-height: 50vh;
}
<div id="wrapper">
   <div id="left" class="txt">Left</div>
   <div id="right" class="txt">Right</div>
</div>

    .container{ 
               width: 50%;  //Your container width here
               height: 50%; //Your container height here
               position: absolute; 
               top: 0; 
               right: 0;  
               bottom: 0; 
               left: 0; 
               margin: auto;
    }

1

상단, 하단, 왼쪽 및 오른쪽을 0으로 설정하십시오.

<html>
<head>
<style>
<div> 
{
position: absolute;
margin: auto;
background-color: lightblue;
width: 100px;
height :100px;
padding: 25px;
top :0;
right :0;
bottom:0;
left:0;
}


</style>
</head>
<body>

<div> I am in the middle</div>

</body>
</html>

1

CSS (요소 display:inline-grid+ grid-auto-flow: row;) 그리드 및 플렉스 박스 (부모 요소)를 사용하여이를 달성 할 수 있습니다display:flex; )를 .

아래 스 니펫 참조

#leftFrame {
  display: flex;
  height: 100vh;
  width: 100%;
}

#tabs {
  display: inline-grid;
  grid-auto-flow: row;
  grid-gap: 24px;
  justify-items: center;
  margin: auto;
}

html,body {
  margin:0;
  padding:0;
}
<div>
<div id=leftFrame>
  <div id=tabs>
    <div>first</div>
    <div>second</div>        
  </div>
</div>
</div>



1

div를 세로 및 가로로 가운데에 배치하는 가장 쉬운 방법은 다음과 같습니다.

<div style="display: table; width: 200px; height: 200px; border: 1px solid black;">
    <div style="display: table-cell; vertical-align: middle; text-align: center;">
        Text Here
    </div>
</div>

하나 더 예 :

.parent {
    display: table; 
    width: 100%; 
    height: 100%;
}

.child {
    display: table-cell; 
    vertical-align: middle;
    text-align: center;
}


<div class="parent">
    <div class="child">
        <h4><u>SERVICE IN BANGLADESH FLEET RESERVE <br> AND <br> RE-ENGAGEMENT ORDER FOR DEFENCE SERVICE</u></h4>
    </div>
</div>

1

이것은 검색 할 때 사람들 이이 페이지에 올 수있는 관련 문제입니다. (100px 사각형) "waiting .."애니메이션 GIF의 div를 가운데에 놓고 싶을 때 :

  .centreDiv {
        position: absolute;
        top: calc(50vh - 50px);
        top: -moz-calc(50vh - 50px);
        top: -webkit-calc(50vh - 50px);
        left: calc(50vw - 50px);
        left: -moz-calc(50vw - 50px);
        left: -webkit-calc(50vw - 50px);
        z-index: 1000; /*whatever is required*/
    }

1

당신이 그것을 원하는 경우 않고 :
인 flexbox / 그리드 / 테이블
또는 없이 :
수직 정렬 : 중간

넌 할 수있어:

HTML

<div class="box">
  <h2 class="box_label">square</h2>
</div>

CSS

.box {
  box-sizing: border-box;
  width: 100px;
  height: 100px;
  text-align: center;
  border: 1px solid black;
}

.box_label {
  box-sizing: border-box;
  display: inline-block;
  transform: translateY(50%);
  text-align: center;
  border: 1px solid black;
}

0

이 작동합니다

.center-div {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    min-height: 100vh;
}
<div class="center-div">Center Div</div>


0

간단! 컨테이너에 디스플레이 플렉스를 사용하고 텍스트에 여백을 자동으로 사용하십시오 !!!!

#hood{

 width : 300px;
 height: 100px;
 border: solid 1px #333333;
 display: flex; 
}

#hood span{

  margin: auto
}



<html>
<head></head>
    <body>
        <div id="hood">
            <span> I Am Centered</span>
        </div>
    </body>
</html>

데모 : https://jsfiddle.net/ay95f08g/

테스트 : MacOs Mojave의 Safari, Chrome, Firefox 및 Opera. (2019 년 2 월 25 일의 모든 최종 업데이트)


0

많은 사람들이 같은 일을했습니다. 페이지 중간에 div를 만들려면 다음 방법을 사용할 수 있습니다.

.center-box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
}
<div class="center-box">
  <h1>Text in center of page</h1>
</div>

건배!


0

가장 간단한 flexbox접근법 :

단일 요소를 세로 및 가로 로 가운데에 배치하는 가장 쉬운 방법 은 플렉스 항목을 만들고 여백을 auto다음 과 같이 설정하는 것입니다 .

Flex 항목에 자동 여백을 적용하면 해당 항목이 자동으로 지정된 여백을 확장하여 Flex 컨테이너의 추가 공간을 차지합니다.

.flex-container {
  height: 150px;
  display: flex;
}

.flex-item {
  margin: auto;
}
<div class="flex-container">
  <div class="flex-item">
    This should be centered!
  </div>
</div>

각 방향으로이 여백을 확장 하면 요소가 컨테이너의 가운데로 정확하게 밀 립니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.