질문자 :shinjuo
텍스트를 div와 정렬하는 가장 효과적인 방법을 찾으려고 합니다. 나는 몇 가지를 시도했지만 아무 것도 작동하지 않는 것 같습니다.
.testimonialText { position: absolute; left: 15px; top: 15px; width: 150px; height: 309px; vertical-align: middle; text-align: center; font-family: Georgia, "Times New Roman", Times, serif; font-style: italic; padding: 1em 0 1em 0; }
<div class="testimonialText"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div>
최신 브라우저에서 이를 수행하는 올바른 방법은 Flexbox를 사용하는 것입니다.
자세한 내용은 이 답변 을 참조하세요.
이전 브라우저에서 작동하는 몇 가지 이전 방법은 아래를 참조하세요.
CSS의 수직 센터링
http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
기사 요약:
CSS 2 브라우저의 경우 display:table
/ display:table-cell
을 사용하여 콘텐츠를 중앙에 배치할 수 있습니다.
샘플은 JSFiddle 에서도 사용할 수 있습니다.
div { border:1px solid green;}
<div style="display: table; height: 400px; overflow: hidden;"> <div style="display: table-cell; vertical-align: middle;"> <div> everything is vertically centered in modern IE8+ and others. </div> </div> </div>
최신 브라우저에서 스타일을 숨기기 위해 #
을 사용하여 이전 브라우저(Internet Explorer 6/7)에 대한 해킹을 스타일로 병합할 수 있습니다.
div { border:1px solid green;}
<div style="display: table; height: 400px; #position: relative; overflow: hidden;"> <div style= "#position: absolute; #top: 50%;display: table-cell; vertical-align: middle;"> <div style=" #position: relative; #top: -50%"> everything is vertically centered </div> </div> </div>
Robert Harveyline-height
속성을 추가해야 하며 해당 속성은 div
높이와 일치해야 합니다. 귀하의 경우:
.center { height: 309px; line-height: 309px; /* same as height! */ }
<div class="center"> A single line. </div>
height
속성을 완전히 제거할 수도 있습니다.
그러나 이것은 한 줄의 텍스트 에만 작동하므로 주의하십시오.
David여기 훌륭한 리소스가 있습니다.
http://howtocenterincss.com/에서 :
CSS에서 센터링은 골치 아픈 일입니다. 다양한 요인에 따라 수많은 방법이 있는 것 같습니다. 이것은 그것들을 통합하고 각 상황에 필요한 코드를 제공합니다.
플렉스박스 사용
이 게시물을 최신 기술로 유지하면서 Flexbox를 사용하여 무언가를 중앙에 배치하는 훨씬 쉬운 방법이 있습니다. Flexbox는 Internet Explorer 9 이하 에서 지원되지 않습니다.
다음은 몇 가지 유용한 리소스입니다.
브라우저 접두사가 있는 JSFiddle
li { display: flex; justify-content: center; align-content: center; flex-direction: column; /* Column | row */ }
<ul> <li> <p>Some Text</p> </li> <li> <p>A bit more text that goes on two lines</p> </li> <li> <p>Even more text that demonstrates how lines can span multiple lines</p> </li> </ul>
또 다른 솔루션
이것은 zerosixthree 에서 가져온 것이며 6줄의 CSS로 무엇이든 중앙에 배치할 수 있습니다.
이 방법은 Internet Explorer 8 이하 에서는 지원되지 않습니다.
jsfiddle
p { text-align: center; position: relative; top: 50%; -ms-transform: translateY(-50%); -webkit-transform: translateY(-50%); transform: translateY(-50%); }
<ul> <li> <p>Some Text</p> </li> <li> <p>A bit more text that goes on two lines</p> </li> <li> <p>Even more text that demonstrates how lines can span multiple lines</p> </li> </ul>
이전 답변
표시된 답변의 링크가 약간 구식이므로 간단하고 브라우저 간 접근 방식이 유용합니다.
JavaScript 또는 CSS 행 높이에 의존하지 않고 정렬되지 않은 목록과 div 모두에서 텍스트를 수직 및 수평 중앙에 배치하는 방법 . 얼마나 많은 텍스트가 있더라도 특정 목록이나 div에 특수 클래스를 적용할 필요가 없습니다(코드는 각각 동일함). 이것은 Internet Explorer 9, Internet Explorer 8, Internet Explorer 7, Internet Explorer 6, Firefox, Chrome, Opera 및 Safari를 포함한 모든 주요 브라우저에서 작동합니다. 최신 브라우저에는 없는 CSS 제한으로 인해 두 가지 특수 스타일시트(Internet Explorer 7용 및 Internet Explorer 6용)가 있습니다.
내가 마지막으로 작업한 프로젝트에서 Internet Explorer 7/6에 대해서는 별로 신경 쓰지 않았기 때문에 약간 제거된 버전을 사용했습니다(즉, Internet Explorer 7 및 6에서 작동하게 만든 항목을 제거함). 다른 사람에게 유용할 수도...
JSFiddle
.outerContainer { display: table; width: 100px; /* Width of parent */ height: 100px; /* Height of parent */ overflow: hidden; } .outerContainer .innerContainer { display: table-cell; vertical-align: middle; width: 100%; margin: 0 auto; text-align: center; } li { background: #ddd; width: 100px; height: 100px; }
<ul> <li> <div class="outerContainer"> <div class="innerContainer"> <div class="element"> <p> <!-- Content --> Content </p> </div> </div> </div> </li> <li> <div class="outerContainer"> <div class="innerContainer"> <div class="element"> <p> <!-- Content --> Content </p> </div> </div> </div> </li> </ul>
Adam Tomatdisplay: flex
사용하면 쉽습니다. 다음 방법을 사용하면 div
의 텍스트가 세로로 가운데에 맞춰집니다.
div { display: -webkit-flex; display: flex; align-items: center; /* More style: */ height: 300px; background-color: #888; }
<div> Your text here. </div>
원하는 경우 수평:
div { display: -webkit-flex; display: flex; align-items: center; justify-content: center; /* More style: */ height: 300px; background-color: #888; }
<div> Your text here. </div>
필요한 브라우저 버전을 확인해야 합니다. 이전 버전에서는 코드가 작동하지 않습니다.
Raul Fernandez Marques다음을 사용하여 임의의 요소를 쉽게 세로로 가운데에 배치합니다.
HTML:
<div style="height: 200px"> <div id="mytext">This is vertically aligned text within a div</div> </div>
CSS:
#mytext { position: relative; top: 50%; transform: translateY(-50%); -webkit-transform: translateY(-50%); }
이렇게 하면 내 div
div
의 정확한 수직 중간에 맞춰집니다. 브라우저에서 이 작업을 수행하려면 브라우저 접두사(예: -webkit-
이것은 텍스트뿐만 아니라 다른 요소에도 적용됩니다.
Stefan van den Akker이것을 시도하고 상위 div에 추가하십시오.
display: flex; align-items: center;
Kerim092디스플레이를 'table-cell'로 설정하고 vertical-align: middle;
:
{ display: table-cell; vertical-align: middle; }
그러나 이것은 허가 없이 http://www.w3schools.com/cssref/pr_class_display.asp 에서 복사한 이 발췌문에 따라 Internet Explorer의 모든 버전에서 지원되지 않습니다.
참고: 값 "inline-table", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-row", "table-row -group" 및 "inherit"는 Internet Explorer 7 및 이전 버전에서 지원되지 않습니다. Internet Explorer 8에는 !DOCTYPE이 필요합니다. Internet Explorer 9는 값을 지원합니다.
다음 표는 http://www.w3schools.com/cssref/pr_class_display.asp 에서도 허용되는 표시 값을 보여줍니다.
![여기에 이미지 설명 입력](https://i.stack.imgur.com/c7nnr.png)
Shadrack B. Orina요즘(Internet Explorer 6-7-8은 더 이상 필요하지 않음) 이 문제에 대해 display: table
display: flex
)을 사용합니다.
이전 브라우저의 경우:
테이블:
.vcenter { display: table; background: #eee; /* optional */ width: 150px; height: 150px; text-align: center; /* optional */ } .vcenter > :first-child { display: table-cell; vertical-align: middle; }
<div class="vcenter"> <p>This is my Text</p> </div>
몸을 풀다:
.vcenter { display: flex; /* <-- Here */ align-items: center; /* <-- Here */ justify-content: center; /* optional */ height: 150px; /* <-- Here */ background: #eee; /* optional */ width: 150px; }
<div class="vcenter"> <p>This is my text</p> </div>
이것은 (실제로는) 이 문제에 대해 내가 가장 좋아하는 솔루션입니다(단순하고 매우 잘 지원되는 브라우저).
div { margin: 5px; text-align: center; display: inline-block; } .vcenter { background: #eee; /* optional */ width: 150px; height: 150px; } .vcenter:before { content: " "; display: inline-block; height: 100%; vertical-align: middle; max-width: 0.001%; /* Just in case the text wrapps, you shouldn't notice it */ } .vcenter > :first-child { display: inline-block; vertical-align: middle; max-width: 99.999%; }
<div class="vcenter"> <p>This is my text</p> </div> <div class="vcenter"> <h4>This is my Text<br/>Text<br/>Text</h4> </div> <div class="vcenter"> <div> <p>This is my</p> <p>Text</p> </div> </div>
Toni Michel CaubetFlexbox는 부모 div 내부의 여러 요소를 가로 및 세로로 가운데에 배치하여 완벽하게 작동했습니다.
HTML 코드:
<div class="parent-div"> <div class="child-div"> <a class="footer-link" href="https://www.github.com/">GitHub</a> <a class="footer-link" href="https://www.facebook.com/">Facebook</a> <p class="footer-copywrite">© 2019 Lorem Ipsum.</p> </div> </div>
CSS 코드:
아래 코드는 부모-div 내부의 모든 요소를 열에서 가로 및 세로 중앙에 배치합니다. 같은 줄(행)에 두 개의 Anchor 요소를 유지하기 위해 child-div를 사용했습니다. 자식 div가 없으면 세 요소(Anchor, Anchor 및 Paragraph)가 모두 부모 div의 열 내부에 서로 쌓입니다. 여기서 자식 div만 부모 div 열 안에 쌓입니다.
/* */ .parent-div { height: 150px; display: flex; flex-direction: column; justify-content: center; }
Mimina다음은 한 줄의 텍스트에 가장 적합한 솔루션입니다.
줄 수를 알고 있는 경우 약간의 조정으로 여러 줄로 된 텍스트에서도 작동할 수 있습니다.
.testimonialText { font-size: 1em; /* Set a font size */ } .testimonialText:before { /* Add a pseudo element */ content: ""; display: block; height: 50%; margin-top: -0.5em; /* Half of the font size */ }
다음은 JSFiddle 입니다.
Craig<!DOCTYPE html> <html> <head> <style> .container { height: 250px; background: #f8f8f8; display: -ms-flexbox; display: -webkit-flex; display: flex; -ms-flex-align: center; align-items: center; -webkit-box-align: center; justify-content: center; } p{ font-size: 24px; } </style> </head> <body> <div class="container"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </div> </body> </html>
Nikit BarochiyaFlexbox를 사용하여 div 내부에서 가운데 텍스트를 세로로 정렬할 수 있습니다.
<div> <p class="testimonialText">This is the testimonial text.</p> </div> div { display: flex; align-items: center; }
Flexbox에 대한 완전한 가이드 에서 이에 대해 자세히 알아볼 수 있습니다.
Cyan Baltazar디스플레이 그리드 및 장소 항목 센터를 사용할 수 있습니다.
.container { width: 200px; height: 200px; border: solid red; display: grid; place-items: center; }
<div class="container"> Lorem, ipsum dolor. </div>
Bladimir Medrano Vargas이 간단한 솔루션을 확인하십시오.
HTML
<div class="block-title"><h3>I'm a vertically centered element</h3></div>
CSS
.block-title { float: left; display: block; width: 100%; height: 88px } .block-title h3 { display: table-cell; vertical-align: middle; height: inherit }
JSFiddle
Davorstable/table-cell에 의존하지 않고 내용을 세로로 정렬하는 더 간단한 방법이 있습니다.
http://jsfiddle.net/bBW5w/1/
여기에 컨테이너의 전체 높이를 가정하는 보이지 않는(width=0) div를 추가했습니다.
Internet Explorer 및 Firefox(최신 버전)에서 작동하는 것 같습니다. 다른 브라우저에서는 확인하지 않았습니다.
<div class="t"> <div> everything is vertically centered in modern IE8+ and others. </div> <div></div> </div>
그리고 물론 CSS:
.t, .t > div:first-child { border: 1px solid green; } .t { height: 400px; } .t > div { display: inline-block; vertical-align: middle } .t > div:last-child { height: 100%; }
Earl Hickey이것은 내가 찾은 가장 깨끗한 솔루션(Internet Explorer 9+)이며 다른 답변에서 생략한 transform-style
을 사용하여 "off by .5 픽셀" 문제에 대한 수정 사항을 추가합니다.
.parent-element { -webkit-transform-style: preserve-3d; -moz-transform-style: preserve-3d; transform-style: preserve-3d; } .element { position: relative; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); }
출처: CSS 3줄로 모든 항목을 수직으로 정렬
JustinHTML:
<div class="col-md-2 ml-2 align-middle"> <label for="option2" id="time-label">Time</label> </div>
CSS :
.align-middle { margin-top: auto; margin-bottom: auto; }
Malith값을 모르는 요소에 대한 간단한 솔루션:
HTML
<div class="main"> <div class="center"> whatever </div> </div>
CSS
.main { position: relative } .center { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50%, -50%); -o-transform: translate(-50%, -50%); }
dimitarAdam Tomat의 답변에 따르면 div 의 텍스트를 정렬 하는 JSFiddle 예제 가 준비되었습니다.
<div class="cells-block"> text<br/>in the block </div>
CSS에서 display:flex 를 사용하여:
.cells-block { display: flex; flex-flow: column; align-items: center; /* Vertically */ justify-content: flex-end; /* Horisontally */ text-align: right; /* Addition: for text's lines */ }
블로그 게시물 에 다른 예 와 몇 가지 설명이 있습니다.
Leon Rom그리드 항목의 자동 여백.
Flexbox와 마찬가지로 그리드 항목에 자동 여백을 적용하면 두 축의 중앙에 정렬됩니다.
.container { display: grid; } .element { margin: auto; }
Sulaymon Hursanov사용하다:
h1 { margin: 0; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); } .container { height: 200px; width: 500px; position: relative; border: 1px solid #eee; }
<div class="container"> <h1>Vertical align text</h1> </div>
이 트릭을 사용하면 중앙에 "left:0"을 추가하여 왼쪽으로 정렬하고 싶지 않다면 아무 것도 정렬할 수 있습니다.
Sanjeet kumarHTML
<div class="relative"><!--used as a container--> <!-- add content here to to make some height and width example:<img src="" alt=""> --> <div class="absolute"> <div class="table"> <div class="table-cell"> Vertical contents goes here </div> </div> </div> </div>
CSS
.relative { position: relative; } .absolute { position: absolute; top: 0; bottom: 0; left: 0; right: 0; background: rgba(0, 0, 0, 0.5); } .table { display: table; height: 100%; width: 100%; text-align: center; color: #fff; } .table-cell { display: table-cell; vertical-align: middle; }
ankit sigdelflex를 사용하는 경우 브라우저의 렌더링 차이에 주의하십시오.
이것은 Chrome과 Internet Explorer 모두에서 잘 작동합니다.
.outer { display: flex; width: 200px; height: 200px; background-color: #ffc; } .inner { display: flex; width: 50%; height: 50%; margin: auto; text-align: center; justify-content: center; align-items: center; background-color: #fcc; }
<div class="outer"><div class="inner">Active Tasks</div></div>
Chrome에서만 작동하는 다음과 비교하십시오.
.outer { display: flex; width: 200px; height: 200px; background-color: #ffc; } .inner { display: flex; width: 50%; height: 50%; margin: auto; background-color: #fcc; }
<div class="outer"> <div class="inner"><span style=" margin: auto;">Active Tasks</span></div> </div>
Roman Pokrovskij이것은 CSS에서 calc()
를 사용하는 div
div
의 또 다른 변형입니다.
<div style="height:300px; border:1px solid green;"> Text in outer div. <div style="position:absolute; height:20px; top:calc(50% - 10px); border:1px solid red;)"> Text in inner div. </div> </div>
다음과 같은 이유로 작동합니다.
-
position:absolute
의 정확한 배치 div
내 div
-
div
의 높이 20px
설정했기 때문에 알고 있습니다. -
calc(50% - 10px)
- 내부 div
중앙에 맞추기 위한 높이의 절반
Stephen Quan이것은 잘 작동합니다.
HTML
<div class="information"> <span>Some text</span> <mat-icon>info_outline</mat-icon> </div>
사스
.information { display: inline-block; padding: 4px 0; span { display: inline-block; vertical-align: middle; } mat-icon { vertical-align: middle; } }
이미지 태그 <mat-icon>
(글꼴임)가 있거나 없는 경우.
Vladflexbox
를 사용할 수 있습니다.
.testimonialText { height: 500px; padding: 1em; display: flex; align-items: center; justify-content: center; border: 1px solid #b4d2d2; }
<div class="testimonialText"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div>
Nidhin Joseph흠, 이 문제를 해결할 수 있는 방법은 분명히 많이 있습니다.
그러나 height:100%
(실제로는 top:0;bottom:0
및 고정 너비)에 절대적으로 위치 <div>
display:table-cell
텍스트를 세로로 가운데에 맞추는 데 작동하지 않았습니다. 내 솔루션에는 내부 스팬 요소가 필요했지만 다른 많은 솔루션도 필요하므로 추가할 수 있습니다.
내 컨테이너는 .label
이고 숫자가 수직으로 가운데에 오기를 원합니다. 나는 절대적으로 top:50%
line-height:0
설정하여 수행했습니다.
<div class="label"><span>1.</span></div>
그리고 CSS는 다음과 같습니다.
.label { position:absolute; top:0; bottom:0; width:30px; } .label>span { position:absolute; top:50%; line-height:0; }
실제 작동 보기: http://jsfiddle.net/jcward/7gMLx/
Jeff WardCSS 그리드를 사용하면 다음과 같은 효과를 얻을 수 있습니다.
.outer { background-color: grey; width: 10rem; height: 10rem; display: grid; justify-items: center; } .inner { background-color: red; align-self: center; }
<div class='outer'> <div class='inner'> Content </div> </div>
ezzatodiv 중앙에 콘텐츠나 이미지를 표시하는 몇 가지 트릭이 있습니다. 답변 중 일부는 정말 훌륭하고 저도 이에 전적으로 동의합니다.
CSS의 절대 수평 및 수직 센터링
http://www.css-jquery-design.com/2013/12/css-techniques-absolute-horizontal-and-vertical-centering-in-css/
예제와 함께 10 개 이상의 기술이 있습니다. 이제 당신이 선호하는 것은 당신에게 달려 있습니다.
의심의 여지가 없습니다. display:table; display:table-Cell
이 더 나은 트릭입니다.
몇 가지 좋은 트릭은 다음과 같습니다.
트릭 1 - display:table; display:table-cell
HTML
<div class="Center-Container is-Table"> <div class="Table-Cell"> <div class="Center-Block"> CONTENT </div> </div> </div>
CSS 코드
.Center-Container.is-Table { display: table; } .is-Table .Table-Cell { display: table-cell; vertical-align: middle; } .is-Table .Center-Block { width: 50%; margin: 0 auto; }
트릭 2 - display:inline-block
HTML
<div class="Center-Container is-Inline"> <div class="Center-Block"> CONTENT </div> </div>
CSS 코드
.Center-Container.is-Inline { text-align: center; overflow: auto; } .Center-Container.is-Inline:after, .is-Inline .Center-Block { display: inline-block; vertical-align: middle; } .Center-Container.is-Inline:after { content: ''; height: 100%; margin-left: -0.25em; /* To offset spacing. May vary by font */ } .is-Inline .Center-Block { max-width: 99%; /* Prevents issues with long content causes the content block to be pushed to the top */ /* max-width: calc(100% - 0.25em) /* Only for Internet Explorer 9+ */ }
트릭 3 - position:relative;position:absolute
<div style="position: relative; background: #ddd; border: 1px solid #ddd; height: 250px;"> <div style="width: 50%; height: 60%; overflow: auto; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; background: #ccc; text-align: center;"> <h4>ABSOLUTE CENTER, <br/> WITHIN CONTAINER.</h4> <p>This box is absolutely centered, horizontally and vertically, within its container</p> </div> </div>
DhirajCSS:
.vertical { display: table-caption; }
수직으로 정렬하려는 항목이 포함된 요소에 이 클래스를 추가합니다.
Jonny Forney출처 : http:www.stackoverflow.com/questions/2939914/how-do-i-vertically-align-text-in-a-div