it-source

CSS를 사용하여 텍스트를 세로 방향으로 중앙에 배치하려면 어떻게 해야 합니까?

criticalcode 2023. 4. 16. 15:13
반응형

CSS를 사용하여 텍스트를 세로 방향으로 중앙에 배치하려면 어떻게 해야 합니까?

는 나나 a a a가 있다<div>되어 있는 이며, 이 하고 싶습니다.<div>이치노

제 사진이 .<div> 예:

#box {
  height: 170px;
  width: 270px;
  background: #000;
  font-size: 48px;
  color: #FFF;
  text-align: center;
}
<div id="box">
  Lorem ipsum dolor sit
</div>

이 목표를 달성하는 가장 좋은 방법은 무엇입니까?

다음의 기본적인 어프로치를 시험할 수 있습니다.

div {
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 2px dashed #f69c55;
}
<div>
  Hello World!
</div>

단, 줄의 높이를 포함 상자 요소와 동일한 높이로 설정하기 때문에 텍스트의 한 줄에만 사용할 수 있습니다.


보다 다양한 접근법

이것은 텍스트를 세로로 정렬하는 또 다른 방법입니다.이 솔루션은 한 줄 및 여러 줄의 텍스트에 대해 작동하지만 여전히 고정 높이 컨테이너가 필요합니다.

div {
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 2px dashed #f69c55;
}
span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}
<div>
  <span>Hello World!</span>
</div>

는 CSS의 만 지정합니다.<div> 위치 " " " "<span><div> 「」는 「높이」가 됩니다.<span>「」를 사용한 vertical-align: middle 다음 그,, . . . . . . . . . . . . . . . . . . .의 회선 <span>블록 내부를 자연스럽게 흐르게 됩니다.


테이블 표시 시뮬레이션

다른 옵션은 지원되지 않는 오래된 브라우저에서는 작동하지 않을 수 있습니다(기본적으로 Internet Explorer 7만 해당).CSS를 사용하여 테이블 동작을 시뮬레이트합니다(테이블은 수직 얼라인먼트를 지원하므로).HTML은 두 번째 예시와 동일합니다.

div {
  display: table;
  height: 100px;
  width: 100%;
  text-align: center;
  border: 2px dashed #f69c55;
}
span {
  display: table-cell;
  vertical-align: middle;
}
<div>
  <span>Hello World!</span>
</div>


절대 포지셔닝 사용

이 기술은 절대 위치 요소를 사용하여 상단, 하단, 왼쪽 및 오른쪽을 0으로 설정합니다.이것은 Smashing Magazine, Absolute Horizontal and Vertical Centering In CSS의 기사에 자세히 설명되어 있습니다.

div {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  width: 100%;
  border: 2px dashed #f69c55;
}
<div>
  <span>Hello World!</span>
</div>

또 다른 방법(여기에 아직 언급되지 않음)은 Flexbox를 사용하는 것입니다.

컨테이너 요소에 다음 코드를 추가합니다.

display: flex;
justify-content: center; /* Align horizontal */
align-items: center; /* Align vertical */

Flexbox 데모 1

.box {
  height: 150px;
  width: 400px;
  background: #000;
  font-size: 24px;
  font-style: oblique;
  color: #FFF;
  text-align: center;
  padding: 0 20px;
  margin: 20px;
  display: flex;
  justify-content: center;
  /* align horizontal */
  align-items: center;
  /* align vertical */
}
<div class="box">
  Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
</div>

또는 Flexbox는 컨테이너를 통해 콘텐츠를 정렬하는 대신 플렉스 컨테이너에 플렉스 항목이 하나만 있는 경우 플렉스 항목의 중심을 자동 마진으로 맞출 수도 있습니다(위의 질문에서 제시된 예시와 같음).

하려면 이 만 하면 .margin:auto

Flexbox 데모 2

.box {
  height: 150px;
  width: 400px;
  background: #000;
  font-size: 24px;
  font-style: oblique;
  color: #FFF;
  text-align: center;
  padding: 0 20px;
  margin: 20px;
  display: flex;
}
.box span {
  margin: auto;
}
<div class="box">
  <span>margin:auto on a flex item centers it both horizontally and vertically</span> 
</div>

NB: 위 내용은 모두 가로로 배치하는 센터링 항목에 적용됩니다.이것은 디폴트 동작이기도 합니다.기본값은flex-directionrow플렉시블 아이템을 세로줄로 배치해야 하는 경우flex-direction: column로 "주축"을 설정해야 합니다.justify-content ★★★★★★★★★★★★★★★★★」align-items이제 속성은 와 반대로 작동합니다.justify-content: center로 중심을 잡고, 세로로 중심을 잡고, 세로로 중심을 잡고, 세로로 중심을 잡다.align-items: center★★★★★★★★★★★★★★★★★★★★★★★」

flex-direction: column를 하다

.box {
  height: 150px;
  width: 400px;
  background: #000;
  font-size: 18px;
  font-style: oblique;
  color: #FFF;
  display: flex;
  flex-direction: column;
  justify-content: center;
  /* vertically aligns items */
  align-items: center;
  /* horizontally aligns items */
}
p {
  margin: 5px;
  }
<div class="box">
  <p>
    When flex-direction is column...
  </p>
  <p>
    "justify-content: center" - vertically aligns
  </p>
  <p>
    "align-items: center" - horizontally aligns
  </p>
</div>

Flexbox의 일부 기능을 확인하고 최대한의 브라우저 지원을 위한 구문을 얻으려면 Flexybox를 사용하는 것이 좋습니다.

또한 현재 브라우저 지원은 매우 우수합니다: caniuse

「」의 크로스 호환성에 는, 「」display: flex ★★★★★★★★★★★★★★★★★」align-items을 사용하다

display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;

이것은, 다음의 CSS 코드를 추가하는 것으로 간단하게 실시할 수 있습니다.

display: table-cell;
vertical-align: middle;

즉, CSS의 외관은 다음과 같습니다.

#box {
  height: 90px;
  width: 270px;
  background: #000;
  font-size: 48px;
  font-style: oblique;
  color: #FFF;
  text-align: center;
  margin-top: 20px;
  margin-left: 5px;
  display: table-cell;
  vertical-align: middle;
}
<div id="box">
  Some text
</div>

참고 및 간단한 답변을 추가하기 위해:

순수 CSS:

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

또는, SAS/SCSS 믹스인으로서:

@mixin vertical-align {
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

사용 방법:

.class-to-center {
    @include vertical-align;
}

Sebastian Ekström의 블로그 투고 Vertical은 CSS의 단 3줄에 모든 것을 맞춥니다.

이 방법을 사용하면 요소가 "반쪽 픽셀"에 배치되기 때문에 요소가 흐릿해질 수 있습니다.이를 위한 해결책은 부모 요소를 preserve-3d로 설정하는 것입니다.다음과 같습니다.

.parent-element {
    -webkit-transform-style: preserve-3d;
    -moz-transform-style: preserve-3d;
    transform-style: preserve-3d;
}

델은 2015+에 살고 있으며 Flex Box는 모든 주요 최신 브라우저에서 지원됩니다.

앞으로 웹사이트가 만들어지는 방식이 될 것이다.

배워라!

모든 신용은 이 링크 소유자 @Sebastian Ekström Link에게 돌아옵니다.이것을 확인해 주세요.행동 규약으로 확인하세요.위의 기사를 읽고 데모 바이올린도 만들었습니다.

단 3줄의 CSS(벤더 프리픽스 제외)로 변환이 가능합니다.translateY는 높이를 모르는 경우에도 원하는 대로 수직으로 중심을 잡습니다.

CSS 속성 변환은 일반적으로 요소의 회전 및 축척에 사용되지만, translateY 기능을 사용하여 요소를 수직으로 정렬할 수 있습니다.일반적으로 이 작업은 절대 위치 설정 또는 선 높이 설정을 사용하여 수행해야 하지만, 요소의 높이를 알거나 한 줄 텍스트에서만 작동해야 합니다.

이를 위해 다음과 같이 적습니다.

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

그것만 있으면 돼절대위치법과 비슷한 기술이지만, 위로는 요소의 높이나 부모의 위치 속성을 설정할 필요가 없습니다.Internet Explorer 9에서도 바로 사용할 수 있습니다.

한층 더 간단하게 하기 위해서, 벤더의 프리픽스와 함께 믹스인이라고 쓸 수 있습니다.

CSS3 플렉스 박스에는 다음과 같은 작은 마법이 있습니다.

/* Important */
section {
    display: flex;
    display: -webkit-flex;
}
section p {
    /* Key Part */
    margin: auto;
}


/* Unimportant, coloring and UI */
section {
    height: 200px;
    width: 60%;
    margin: auto;
    border-radius: 20px;
    border: 3px solid orange;
    background-color: gold;
}
section p {
    text-align: center;
    font-family: Cantarell, Calibri;
    font-size: 15px;
    background-color: yellow;
    border-radius: 20px;
    padding: 15px;
}
<section>
    <p>
        I'm a centered box!<br/>
        Flexboxes are great!
    </p>
</section>

힌트: 텍스트를 가운데에 배치하려면 위의 "키 부품"으로 표시된 행을 다음 중 하나의 행으로 바꿉니다.

  1. 수직만:

    margin: auto 0;
    
  2. 수평만:

    margin: 0 auto;
    

가 알기로는, 이 은 그리드와 되어 있습니다(즉, 즉, 이 기술은 그리드와 함께 할 수 있습니다.display: grid도 참조해 주세요도 참조해 주세요.

Flexbox를 사용하는 다른 옵션은 다음과 같습니다.

#container {
  display: flex;
  height: 200px;
  background: orange;
}

.child {
  margin: auto;
}
<div id="container">
  <div class="child">
    <span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Molestiae, nemo.</span>
  </div>
</div>

결과

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

여기 CSS에서의 중심화에 대한 훌륭한 기사가 있습니다.이것 좀 봐봐요.

유연한 어프로치

div {
  width: 250px;
  min-height: 50px;
  line-height: 50px;
  text-align: center;
  border: 1px solid #123456;
  margin-bottom: 5px;
}
span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br />
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br />
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>
<div>
  <span>Lorem ipsum dolor sit amet.</span>
</div>
<div>

앞의 회답은, 그 화면폭(응답 없음)에서만 동작합니다.반응성을 위해 플렉스를 사용해야 합니다.

예:

div { display:flex; align-items:center; }

정답으로 인정된 솔루션은 사용하기에 완벽합니다.line-height 있는 이 방법은 하지 않습니다.div는 텍스트가 2줄로 감겨져 있는 경우입니다.

텍스트가 줄바꿈되어 있거나 div 안에 여러 줄에 있는 경우 이 옵션을 사용해 보십시오.

#box
{
  display: table-cell;
  vertical-align: middle;
}

자세한 것은, 다음을 참조해 주세요.

다음의 코드 스니펫을 참조로 사용할 수 있습니다.그것은 나에게 매력적으로 작용하고 있다.

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

body {
  display: table;
}

.centered-text {
  text-align: center;
  display: table-cell;
  vertical-align: middle;
}
<div class="centered-text">
  <h1>Yes, it's my landing page</h1>
  <h2>Under construction, coming soon!!!</h2>
</div>

상기 코드 스니펫의 출력은 다음과 같습니다.

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

다음 솔루션을 사용해 보십시오.

.EXTENDER {
    position: absolute;
    top: 0px;
    left: 0px;
    bottom: 0px;
    right: 0px;
    width: 100%;
    height: 100%;
    overflow-y: hidden;
    overflow-x: hidden;
}

.PADDER-CENTER {
    width: 100%;
    height: 100%;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-box-pack: center;
    -moz-box-pack: center;
    -ms-flex-pack: center;
    -webkit-justify-content: center;
    justify-content: center;
    -webkit-box-align: center;
    -moz-box-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;
}
<div class="EXTENDER">
  <div class="PADDER-CENTER">
    <div contentEditable="true">Edit this text...</div>
  </div>
</div>

CSS+를 사용하여 구축.

아래 속성을 사용할 수도 있습니다.

display: flex; 
align-content: center; 
justify-content : center;

다른 방법:

」를 하지 .height「」의 div , 을 사용합니다.padding:그 효과를 얻기 위해.줄 높이와 마찬가지로 텍스트가 한 줄일 경우에만 작동합니다.이렇게 하면 내용이 더 많아도 텍스트는 중앙에 배치되지만 div 자체는 약간 커집니다.

따라서 다음과 같은 방법을 사용하는 대신

div {
  height: 120px;
  line-height: 120px;
}

다음과 같이 말할 수 있습니다.

div {
   padding: 60px 0; /* Maybe 60 minus font-size divided by two, if you want to be exact */
}

.paddingdiv로로 합니다.60px및과 .padding을 0으로 div높이 120픽셀(글꼴 높이 포함)로 텍스트를 div 중앙에 수직으로 배치합니다.

writing-mode루트는 문제 해결이 깔끔하고 폭넓은 지원을 얻을 수 있다고 생각합니다.

.vertical {
  //border: 1px solid green;
  writing-mode: vertical-lr;
  text-align: center;
  height: 100%;
  width: 100%;
}
.horizontal {
  //border: 1px solid blue;
  display: inline-block;
  writing-mode: horizontal-tb;
  width: 100%;
  text-align: center;
}
.content {
  text-align: left;
  display: inline-block;
  border: 1px solid #e0e0e0;
  padding: .5em 1em;
  border-radius: 1em;
}
<div class="vertical">
  <div class="horizontal">
    <div class="content">
      I'm centered in the vertical and horizontal thing
    </div>
  </div>
</div>

물론 이것은 필요한 모든 차원(부모의 100% 제외)에서 작동합니다.경계선을 허물면 익숙해지는 데 도움이 될 거예요.

JSFiddle 데모입니다.

Caniuse 지원: 85.22% + 6.26% = 91.48% (Internet Explorer도 지원)

모든 수직 정렬 요구에 대응합니다.

이 믹스인을 선언합니다.

@mixin vertical-align($position: relative) {
  position: $position;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

그런 다음 요소에 포함합니다.

.element{
    @include vertical-align();
}

더 좋은 생각이네요이렇게도 할 수 있어요.

body,
html {
  height: 100%;
}

.parent {
  white-space: nowrap;
  height: 100%;
  text-align: center;
}

.parent:after {
  display: inline-block;
  vertical-align: middle;
  height: 100%;
  content: '';
}

.centered {
  display: inline-block;
  vertical-align: middle;
  white-space: normal;
}
<div class="parent">
  <div class="centered">
    <p>Lorem ipsum dolor sit amet.</p>
  </div>
</div>

한 줄의 텍스트(또는 한 글자)에 대해 다음 기술을 사용할 수 있습니다.

다음 경우에 사용할 수 있습니다.#box는 비고정, 상대높이 %를 가지고 있습니다.

<div id="box"></div>
#box::before {
    display: block;
    content: "";
    height: 50%;
}

#box::after {
    vertical-align: top;
    line-height: 0;
    content: "TextContent";
}

JsBin(CSS 편집 용이) 또는 JsFiddle(결과 프레임 높이 변경 용이)에서 라이브 데모를 참조하십시오.

내부 텍스트를 CSS가 아닌 HTML로 배치하려면 텍스트 콘텐츠를 추가 인라인 요소로 랩하여 편집해야 합니다.#box::after(그리고 물론)content:속성을 삭제해야 합니다.)

예를들면,<div id="box"><span>TextContent</span></div>이 경우,#box::after로 대체해야 한다.#box span.

Explorer 8을 교체해야 .:::.

간단하고 다용도적인 방법은 다음과 같습니다(Michielvoo의 테이블 접근법).

[ctrv]{
    display: table !important;
}

[ctrv] > *{ /* Addressing direct descendants */
      display: table-cell;
      vertical-align: middle;
      // text-align: center; /* Optional */
}

부모 태그에서 이 속성(또는 동등한 클래스)을 사용하면 많은 자녀가 정렬할 수 있습니다.

<parent ctrv>  <ch1/>  <ch2/>   </parent>

변환 속성을 사용해 보십시오.

 #box {
  height: 90px;
  width: 270px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
 <div Id="box">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>

매우 심플하고 강력한 솔루션으로 중앙을 수직으로 정렬할 수 있습니다.

.outer-div {
  height: 200px;
  width: 200px;
  text-align: center;
  border: 1px solid #000;
}

.inner {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  color: red;
}
<div class="outer-div">
  <span class="inner">No data available</span>
</div>

는 화면 합니다.div 표시:

.center-screen {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  min-height: 100vh;
}
 <html>
 <head>
 </head>
 <body>
 <div class="center-screen">
 I'm in the center
 </div>
 </body>
 </html>

것은, 을 해 주세요.flex 여기 있습니다.

다음 코드를 사용해 보십시오.

display: table-cell;
vertical-align: middle;

div {
  height: 80%;
  width: 100%;
  text-align: center;
  display: table-cell;
  vertical-align: middle;
  background: #4CAF50;
  color: #fff;
  font-size: 50px;
  font-style: italic;
}
<div>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
</div>

라인의 높이와 div 높이의 호흡에 대한 니즈를 해소하기 위해 미치엘부의 답변을 연장하고 싶습니다.기본적으로 다음과 같이 단순화된 버전입니다.

div {
  width: 250px;
  /* height: 100px;
  line-height: 100px; */
  text-align: center;
  border: 1px solid #123456;
  background-color: #bbbbff;
  padding: 10px;
  margin: 10px;
}

span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}
<div>
  <span>All grown-ups were once children... but only few of them remember it</span>
</div>

<div>
  <span>And now here is my secret, a very simple secret: It is only with the heart that one can see rightly; what is essential is invisible to the eye.</span>
</div>

의 되어 있습니다.cssfixed-heightdiv.

클릭할 수 있는 코끼리를 세로 중앙에 배치해야 했지만 Internet Explorer 9의 이상한 점을 피하기 위해 테이블을 사용하지 않았습니다.

결국 내 요구에 가장 적합한 CSS를 찾았고 Firefox, Chrome 및 Internet Explorer 11에 적합합니다.안타깝게도 인터넷 익스플로러 9은 아직도 나를 비웃고 있어...

div {
  border: 1px dotted blue;
  display: inline;
  line-height: 100px;
  height: 100px;
}

span {
  border: 1px solid red;
  display: inline-block;
  line-height: normal;
  vertical-align: middle;
}

.out {
  border: 3px solid silver;
  display: inline-block;
}
<div class="out" onclick="alert(1)">
  <div> <span><img src="http://www.birdfolk.co.uk/littleredsolo.png"/></span> </div>
  <div> <span>A lovely clickable option.</span> </div>
</div>

<div class="out" onclick="alert(2)">
  <div> <span><img src="http://www.birdfolk.co.uk/bang2/Ship01.png"/></span> </div>
  <div> <span>Something charming to click on.</span> </div>
</div>

물론 국경은 필요 없지만 어떻게 작동하는지 볼 수 있습니다.

CSS에서는 다음과 같은 포지셔닝 방법을 사용할 수 있습니다.

여기서 결과를 확인합니다.

HTML:

<div class="relativediv">
  <p>
    Make me vertical align as center
  </p>
</div>

CSS:

.relativediv {
    position: relative;
    border: 1px solid #DDD;
    height: 300px;
    width: 300px
}
.relativediv p {
    position: absolute;
    top: 50%;
    transfrom: translateY(-50%);
}

해 볼 수 뜻입니다.display:table-cell ★★★★★★★★★★★★★★★★★」vertical-align:middle.

예:

#box
{
  display: table-cell;
  vertical-align: middle;
  height: 90px;
  width: 270px;
  background: #000;
  font-size: 48px;
  font-style: oblique;
  color: #FFF;
  text-align: center;
  margin-top: 20px;
  margin-left: 5px;
}
<div Id="box">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>

buttondiv3D 영상입니다.

#box
{
  height: 120px;
  width: 300px;
  background: #000;
  font-size: 48px;
  font-style: oblique;
  color: #FFF;
}
<button Id="box" disabled>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</button>

절대 포지셔닝 및 스트레칭

위의 방법과 마찬가지로 이 방법은 부모 요소와 자녀 요소 각각에 상대적인 요소와 절대적인 요소의 위치를 설정하는 것으로 시작합니다.그것과는 사정이 다르다.

아래 코드에서는 다시 한 번 이 방법을 사용하여 아이를 수평과 수직으로 중심을 맞췄습니다. 단, 수직 센터링에만 사용할 수 있습니다.

HTML

<div id="parent">
    <div id="child">Content here</div>
</div>

CSS

#parent {position: relative;}
#child {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 50%;
    height: 30%;
    margin: auto;
}

이 방법에서는 위쪽, 아래쪽, 오른쪽 및 왼쪽 베일을 0으로 설정하여 하위 요소가 네 모서리까지 모두 늘어나도록 시도하는 것이 좋습니다.자식 요소가 부모 요소보다 작기 때문에 네 모서리 모두에 도달할 수 없습니다.

그러나 auto를 4변 모두 여백으로 설정하면 반대 여백이 같아지고 자녀 div가 부모 div의 중앙에 표시됩니다.

유감스럽게도 위의 내용은 Internet Explorer 7 이하에서는 사용할 수 없습니다.이전 방법과 마찬가지로 child div 내의 콘텐츠가 너무 커져서 숨겨질 수 있습니다.

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

요소의 CSS 속성에 이 작은 코드를 추가합니다.대박이다.해봐!

언급URL : https://stackoverflow.com/questions/8865458/how-do-i-vertically-center-text-with-css

반응형