요소를 수평으로 중앙에 배치하려면 어떻게 해야 합니까?
하면 수평으로 중심을 잡을 수 있습니까?<div>
大인내타에부의▁within<div>
CSS를 사용하시겠습니까?
<div id="outer">
<div id="inner">Foo foo</div>
</div>
와 함께flexbox
로 중심을 은 매우 .div 수평수중직심로스으타것를는매쉽은습다니우하링일과▁it.
#inner {
border: 0.05em solid black;
}
#outer {
border: 0.05em solid red;
width:100%;
display: flex;
justify-content: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
분할 중심을 수직으로 정렬하려면 특성을 사용합니다.align-items: center
.
기타 솔루션
은 이 CSS를 내부의 CSS에 할 수 .<div>
:
#inner {
width: 50%;
margin: 0 auto;
}
물설정필없습다니는요할론▁the다없니습▁of▁havet▁don를 설정할 필요는 없습니다.width
50%
하는 함하는폭작폭은보보다 폭<div>
효과가 있을 것입니다. 그margin: 0 auto
실제 센터링을 하는 것입니다.
Internet Explorer 8(및 그 이상)을 대상으로 하는 경우 대신 다음을 사용하는 것이 좋습니다.
#inner {
display: table;
margin: 0 auto;
}
한 요소를 합니다.width
.
작업 예제:
#inner {
display: table;
margin: 0 auto;
border: 1px solid black;
}
#outer {
border: 1px solid red;
width:100%
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
않다면.div
당신은 다음과 같은 것을 할 수 있습니다.
#outer {
width: 100%;
text-align: center;
}
#inner {
display: inline-block;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
그것이 내면을 만듭니다.div
수있인요로로 수 있는 text-align
.
가장 좋은 방법은 CSS3입니다.
이전 상자 모델(사용되지 않음)
display: box
그 은 그고그특들성리들▁and특성▁its▁properbox-pack
,box-align
,box-orient
,box-direction
등이 플렉스박스로 대체되었습니다.이러한 장치는 여전히 작동할 수 있지만 프로덕션에서 사용하지 않는 것이 좋습니다.
#outer {
width: 100%;
/* Firefox */
display: -moz-box;
-moz-box-pack: center;
-moz-box-align: center;
/* Safari and Chrome */
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align: center;
/* W3C */
display: box;
box-pack: center;
box-align: center;
}
#inner {
width: 50%;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
편의성에 ▁the▁▁also다▁according니를 사용할 수도 있습니다.box-orient, box-flex, box-direction
특성.
Flexbox를 사용한 최신 박스 모델
#outer {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
하위 요소 중심 설정에 대해 자세히 알아보기
이를 통해 박스 모델이 최상의 접근 방식인 이유를 설명할 수 있습니다.
#centered {
position: absolute;
left: 50%;
margin-left: -100px;
}
<div id="outer" style="width:200px">
<div id="centered">Foo foo</div>
</div>
상위 요소(예: 상대, 고정, 절대 또는 고정)가 배치되어 있는지 확인합니다.
div의 , 은 만약당의당신의너모비를면, 은사수있다습니용할당다신른을 사용할 수 .transform:translateX(-50%);
마이너스 마진 대신에
CSS calc()를 사용하면 코드가 더 단순해집니다.
.centered {
width: 200px;
position: absolute;
left: calc(50% - 100px);
}
원리는 여전히 동일합니다. 가운데에 항목을 놓고 너비를 보정합니다.
이 예제는 수직 및 수평으로 사용하는 방법을 보여주기 위해 작성되었습니다. align
.
코드는 기본적으로 다음과 같습니다.
#outer {
position: relative;
}
그리고...
#inner {
margin: auto;
position: absolute;
left:0;
right: 0;
top: 0;
bottom: 0;
}
그리고 그것은 앞으로도 계속될 것입니다.center
화면 크기를 조정할 때도 사용할 수 있습니다.
을 사용하여 하는 CSS 3 했습니다.display:box
.
이 구문은 구식이므로 더 이상 사용하면 안 됩니다.[이 게시물도 참조]
따라서 완전성을 위해 여기에 플렉시블 박스 레이아웃 모듈을 사용하여 CSS 3을 중앙에 배치하는 최신 방법이 있습니다.
따라서 다음과 같은 간단한 마크업이 있습니다.
<div class="box">
<div class="item1">A</div>
<div class="item2">B</div>
<div class="item3">C</div>
</div>
...그리고 항목을 상자 안에 중앙에 배치하려면 다음과 같이 상위 요소(.box)에 필요한 사항을 확인하십시오.
.box {
display: flex;
flex-wrap: wrap; /* Optional. only if you want the items to wrap */
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
.box {
display: flex;
flex-wrap: wrap;
/* Optional. only if you want the items to wrap */
justify-content: center;
/* For horizontal alignment */
align-items: center;
/* For vertical alignment */
}
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
.box {
height: 200px;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
border: 2px solid tomato;
}
.box div {
margin: 0 10px;
width: 100px;
}
.item1 {
height: 50px;
background: pink;
}
.item2 {
background: brown;
height: 100px;
}
.item3 {
height: 150px;
background: orange;
}
<div class="box">
<div class="item1">A</div>
<div class="item2">B</div>
<div class="item3">C</div>
</div>
Flexbox에 대해 이전 구문을 사용하는 이전 브라우저를 지원해야 하는 경우 여기를 참조하십시오.
된 너비를 마진을 원하지 고정비너를설정않고추지원추않경가우는하지마을진가하▁if▁add추가,경우▁and▁you않는▁a▁margin고정▁extra▁don원▁don▁width하지▁fixed를 추가하세요.display: inline-block
당신의 요소에.
사용할 수 있는 항목:
#element {
display: table;
margin: 0 auto;
}
높이와 너비를 알 수 없는 div 중심 맞추기
가로 세로.상당히 현대적인 브라우저(파이어폭스, Safari/WebKit, Chrome, Internet & Explorer & 10, Opera 등)와 함께 작동합니다.
.content {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<div class="content">This works with any content</div>
을 합니다.width
트세를 합니다.margin-left
그리고.margin-right
auto
하지만 그건 수평으로만 가능합니다.만약 당신이 두 가지 방법을 모두 원한다면, 당신은 그냥 두 가지 방법으로 할 것입니다.실험하는 것을 두려워하지 마세요. 그것은 당신이 어떤 것도 깨뜨릴 것 같지 않습니다.
너비를 지정하지 않으면 중심에 배치할 수 없습니다.그렇지 않으면 기본적으로 전체 수평 공간이 사용됩니다.
#outer {
width: 100%;
height: 100%;
display: box;
box-orient: horizontal;
box-pack: center;
box-align: center;
}
제가 주로 하는 방법은 절대 위치를 사용하는 것입니다.
#inner{
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
position: absolute;
}
외부 디브는 이것이 작동하기 위해 추가적인 속성이 필요하지 않습니다.
저는 최근에 "숨겨진" 디바를 중앙에 배치해야 했습니다.display:none;
페이지 중앙에 있어야 하는 표 형식이 있습니다.숨겨진 div를 표시하기 위해 다음과 같은 jQuery 코드를 작성하여 CSS 콘텐츠를 테이블의 자동 생성 폭으로 업데이트하고 여백을 변경하여 중심을 맞춥니다. (표시 토글은 링크를 클릭하면 트리거되지만 이 코드는 표시할 필요가 없었습니다.)
참고: 이 코드를 공유하는 이유는 Google에서 이 스택 오버플로 솔루션으로 나를 데려왔고 숨겨진 요소가 너비가 없고 표시된 후까지 크기를 조정하거나 중심을 조정할 수 없다는 점을 제외하고는 모두 작동했을 것이기 때문입니다.
$(function(){
$('#inner').show().width($('#innerTable').width()).css('margin','0 auto');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inner" style="display:none;">
<form action="">
<table id="innerTable">
<tr><td>Name:</td><td><input type="text"></td></tr>
<tr><td>Email:</td><td><input type="text"></td></tr>
<tr><td>Email:</td><td><input type="submit"></td></tr>
</table>
</form>
</div>
Firefox 및 Chrome의 경우:
<div style="width:100%;">
<div style="width: 50%; margin: 0px auto;">Text</div>
</div>
Internet Explorer, Firefox 및 Chrome의 경우:
<div style="width:100%; text-align:center;">
<div style="width: 50%; margin: 0px auto; text-align:left;">Text</div>
</div>
그text-align:
속성은 최신 브라우저의 경우 선택 사항이지만 기존 브라우저를 지원하려면 Internet Explorer Quirks 모드에서 필요합니다.
사용:
#outerDiv {
width: 500px;
}
#innerDiv {
width: 200px;
margin: 0 auto;
}
<div id="outerDiv">
<div id="innerDiv">Inner Content</div>
</div>
중 또 3을 입니다.transform
기여하다.
#outer {
position: relative;
}
#inner {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
그 ㅠㅠtranslateX(-50%)
설정합니다.#inner
요소가 50% 왼쪽에 있습니다.수직 정렬에도 동일한 트릭을 사용할 수 있습니다.
여기 수평 및 수직 정렬을 보여주는 피들이 있습니다.
자세한 내용은 Mozilla Developer Network에 있습니다.
자신의 블로그에 '미지의 중심'에 훌륭한 글을 쓴 크리스 코이에.여러 솔루션을 정리한 것입니다.저는 이 질문에 게시되지 않은 것을 올렸습니다.Flexbox 솔루션보다 더 많은 브라우저 지원을 제공하며 사용자는display: table;
다른 것들을 깨뜨릴 수도 있습니다.
/* This parent can be any width and height */
.outer {
text-align: center;
}
/* The ghost, nudged to maintain perfect centering */
.outer:before {
content: '.';
display: inline-block;
height: 100%;
vertical-align: middle;
width: 0;
overflow: hidden;
}
/* The element to be centered, can
also be of any width and height */
.inner {
display: inline-block;
vertical-align: middle;
width: 300px;
}
최근에 다음과 같은 접근법을 발견했습니다.
#outer {
position: absolute;
left: 50%;
}
#inner {
position: relative;
left: -50%;
}
두 요소가 올바르게 작동하려면 너비가 같아야 합니다.
div#outer {
height: 120px;
background-color: red;
}
div#inner {
width: 50%;
height: 100%;
background-color: green;
margin: 0 auto;
text-align: center; /* For text alignment to center horizontally. */
line-height: 120px; /* For text alignment to center vertically. */
}
<div id="outer" style="width:100%;">
<div id="inner">Foo foo</div>
</div>
만약 당신이 부모 밑에 많은 아이들을 둔다면, 당신의 CSS 콘텐츠는 fiddle의 이 예시와 같아야 합니다.
HTML 콘텐츠 모양은 다음과 같습니다.
<div id="outer" style="width:100%;">
<div class="inner"> Foo Text </div>
<div class="inner"> Foo Text </div>
<div class="inner"> Foo Text </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> Foo Text </div>
</div>
수평으로만 중심 맞추기
내 경험에 따르면 상자를 수평으로 가운데에 두는 가장 좋은 방법은 다음 속성을 적용하는 것입니다.
컨테이너:
- 했어야 했습니다
text-align: center;
내용 상자:
- 했어야 했습니다
display: inline-block;
데모:
.container {
width: 100%;
height: 120px;
background: #CCC;
text-align: center;
}
.centered-content {
display: inline-block;
background: #FFF;
padding: 20px;
border: 1px solid #000;
}
<div class="container">
<div class="centered-content">
Center this!
</div>
</div>
수평 및 수직으로 중심 맞추기
내 경험에 따르면 상자의 중심을 수직 및 수평으로 맞추는 가장 좋은 방법은 추가 용기를 사용하고 다음 속성을 적용하는 것입니다.
외부 컨테이너:
- 했어야 했습니다
display: table;
내부 컨테이너:
- 했어야 했습니다
display: table-cell;
- 했어야 했습니다
vertical-align: middle;
- 했어야 했습니다
text-align: center;
내용 상자:
- 했어야 했습니다
display: inline-block;
데모:
.outer-container {
display: table;
width: 100%;
height: 120px;
background: #CCC;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
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>
플렉스박스
display: flex
블록 요소처럼 작동하며 Flexbox 모델에 따라 컨텐츠를 레이아웃합니다.와 함께 작동합니다.
참고:Flexbox는 Internet Explorer를 제외한 모든 브라우저와 호환됩니다.브라우저 호환성의 전체 최신 목록은 Internet Explorer에서 작동하지 않는 플렉스를 참조하십시오.
#inner {
display: inline-block;
}
#outer {
display: flex;
justify-content: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
텍스트 정렬: 가운데
인라인 내용 적용은 줄 상자 내에서 중앙에 배치됩니다.그러나 내부 디브가 기본적으로 가지고 있기 때문에.width: 100%
특정 너비를 설정하거나 다음 중 하나를 사용해야 합니다.
#inner {
display: inline-block;
}
#outer {
text-align: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
여백: 0 자동
를 사용하는 것은 또 다른 옵션이며 이전 브라우저 호환성에 더 적합합니다.와 함께 작동합니다.
#inner {
display: table;
margin: 0 auto;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
변환
transform: translate
CSS 시각적 서식 모델의 좌표 공간을 수정할 수 있습니다.이를 사용하여 요소를 변환, 회전, 축척 및 왜곡할 수 있습니다.수평으로 중심을 맞추려면 및 가 필요합니다.
#inner {
position: absolute;
left: 50%;
transform: translate(-50%, 0%);
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
<center>
되지 않음사용되지 않음)
태그는 HTML 대신 사용됩니다.이 기능은 이전 브라우저와 대부분의 새 브라우저에서 작동하지만 이 기능이 구식이고 웹 표준에서 제거되었기 때문에 좋은 방법으로 간주되지 않습니다.
#inner {
display: inline-block;
}
<div id="outer">
<center>
<div id="inner">Foo foo</div>
</center>
</div>
이 방법도 잘 작동합니다.
div.container {
display: flex;
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
너용이.<div>
유일한 조건은 그것입니다.height
그리고.width
용기의 크기보다 커서는 안 됩니다.
가장 쉬운 방법:
#outer {
width: 100%;
text-align: center;
}
#inner {
margin: auto;
width: 200px;
}
<div id="outer">
<div id="inner">Blabla</div>
</div>
Flex는 97% 이상의 브라우저 지원 서비스를 제공하며 몇 줄 안에 이러한 문제를 해결하는 가장 좋은 방법일 수 있습니다.
#outer {
display: flex;
justify-content: center;
}
내용의 너비를 알 수 없는 경우 다음 방법을 사용할 수 있습니다.다음 두 가지 요소가 있다고 가정합니다.
.outer
.inner
너비가 설정되지 않았지만 최대 너비를 지정할 수 있습니다.
요소의 계산된 너비가 각각 1000픽셀과 300픽셀이라고 가정합니다.다음과 같이 진행합니다.
- 다
.inner
東京의.center-helper
- 만들다
.center-helper
블록; 라인블록됩; 크한가니다기와 가 됩니다..inner
300픽셀 너비로 만듭니다. - 시
.center-helper
상위 항목에 대해 오른쪽으로 50%, 왼쪽이 500픽셀, 바깥쪽에 배치됩니다. - 시
.inner
상위 항목에 대해 50% 왼쪽으로 이동합니다. 그러면 왼쪽이 -150픽셀 wrt. 중앙 도우미에 배치됩니다. 이는 왼쪽이 500 - 150픽셀 wrt. 바깥쪽에 있음을 의미합니다. - 에
.outer
가로 스크롤 막대를 방지하기 위해 숨깁니다.
데모:
body {
font: medium sans-serif;
}
.outer {
overflow: hidden;
background-color: papayawhip;
}
.center-helper {
display: inline-block;
position: relative;
left: 50%;
background-color: burlywood;
}
.inner {
display: inline-block;
position: relative;
left: -50%;
background-color: wheat;
}
<div class="outer">
<div class="center-helper">
<div class="inner">
<h1>A div with no defined width</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br>
Duis condimentum sem non turpis consectetur blandit.<br>
Donec dictum risus id orci ornare tempor.<br>
Proin pharetra augue a lorem elementum molestie.<br>
Nunc nec justo sit amet nisi tempor viverra sit amet a ipsum.</p>
</div>
</div>
</div>
당신은 이런 것을 할 수 있습니다.
#container {
display: table;
width: <width of your container>;
height: <height of your container>;
}
#inner {
width: <width of your center div>;
display: table-cell;
margin: 0 auto;
text-align: center;
vertical-align: middle;
}
이는또정다니됩렬도 됩니다.#inner
수직으로원하지 않는 경우 다음을 제거합니다.display
그리고.vertical-align
속성;
여기 당신이 가장 빠른 방법으로 원하는 것이 있습니다.
#outer {
margin - top: 100 px;
height: 500 px; /* you can set whatever you want */
border: 1 px solid# ccc;
}
#inner {
border: 1 px solid# f00;
position: relative;
top: 50 % ;
transform: translateY(-50 % );
}
사용할 수 있습니다.display: flex
당신의 외부 디브와 수평으로 중심을 잡으려면 당신은 추가해야 합니다.justify-content: center
#outer{
display: flex;
justify-content: center;
}
또는 더 많은 아이디어를 위해 w3개의 학교 - CSS 플렉스 속성을 방문할 수 있습니다.
저는 모든 상황에 적합하지만 JavaScript를 사용하는 솔루션을 찾을 수 있었습니다.
구조는 다음과 같습니다.
<div class="container">
<div class="content">Your content goes here!</div>
<div class="content">Your content goes here!</div>
<div class="content">Your content goes here!</div>
</div>
다음은 JavaScript 스니펫입니다.
$(document).ready(function() {
$('.container .content').each( function() {
container = $(this).closest('.container');
content = $(this);
containerHeight = container.height();
contentHeight = content.height();
margin = (containerHeight - contentHeight) / 2;
content.css('margin-top', margin);
})
});
응답형 접근 방식으로 사용하려면 다음을 추가할 수 있습니다.
$(window).resize(function() {
$('.container .content').each( function() {
container = $(this).closest('.container');
content = $(this);
containerHeight = container.height();
contentHeight = content.height();
margin = (containerHeight - contentHeight) / 2;
content.css('margin-top', margin);
})
});
제가 찾은 한 가지 옵션은 다음과 같습니다.
모두가 다음을 사용하라고 말합니다.
margin: auto 0;
하지만 다른 선택지가 있습니다.상위 div에 대해 이 속성을 설정합니다.언제든지 완벽하게 작동합니다.
text-align: center;
보세요, 아이들이 센터에 가요.
마지막으로 CSS입니다.
#outer{
text-align: center;
display: block; /* Or inline-block - base on your need */
}
#inner
{
position: relative;
margin: 0 auto; /* It is good to be */
}
언급URL : https://stackoverflow.com/questions/114543/how-can-i-horizontally-center-an-element
'programing' 카테고리의 다른 글
mongodb에서 최소값을 찾는 방법 (0) | 2023.05.05 |
---|---|
개인 저장소 복제(Github) (0) | 2023.05.05 |
List는 삽입 순서를 보장합니까? (0) | 2023.05.05 |
바인딩 항목WPF 데이터 그리드의 ComboBox 열 원본 (0) | 2023.05.05 |
DateTime 속성의 기본값을 DateTime으로 설정하는 중입니다.이제 시스템 안으로 들어갑니다.ComponentModel 기본값 특성입니다. (0) | 2023.04.25 |