div에서 요소를 수직으로 정렬하는 방법은 무엇입니까?
두 개의 이미지와 h1
. 이들 모두는 div 내에서 서로 나란히 수직으로 정렬되어야합니다.
이미지 중 하나는 absolute
div 내에 위치 해야합니다 .
모든 일반 브라우저에서 작동하는 데 필요한 CSS는 무엇입니까?
<div id="header">
<img src=".." ></img>
<h1>testing...</h1>
<img src="..."></img>
</div>
와우,이 문제는 인기가 있습니다. 그것은 vertical-align
재산 에 대한 오해에 근거 합니다. 이 훌륭한 기사는 이에 대해 설명합니다.
vertical-align
Gavin Kistner의 이해 또는 "컨텐츠를 수직으로 중앙에 배치하는 방법" .
“How to center in CSS” 는 다양한 상황에 필요한 CSS 센터링 속성을 찾는 데 도움이되는 훌륭한 웹 도구입니다.
간단히 말해서 (그리고 링크 부패를 방지하기 위해) :
- 인라인 요소 (및 인라인 요소 만) 는를 통해 컨텍스트에서 세로로 정렬 할 수 있습니다
vertical-align: middle
. 그러나 "컨텍스트"는 전체 상위 컨테이너 높이가 아니라 그들이있는 텍스트 라인의 높이입니다. jsfiddle 예제 - 블록 요소의 경우 수직 정렬이 더 어렵고 특정 상황에 따라 크게 달라집니다.
- 내부 요소가있을 경우 고정 높이를 , 당신은 위치를 만들 수 있습니다
absolute
및 지정height
,margin-top
및top
위치. jsfiddle 예 - 중앙에있는 요소 가 한 줄로 구성 되고 부모 높이가 고정 되어있는 경우 컨테이너의
line-height
높이를 채우기 만하면됩니다 . 이 방법은 내 경험상 매우 다양합니다. jsfiddle 예 - … 더 많은 특별한 경우가 있습니다.
- 내부 요소가있을 경우 고정 높이를 , 당신은 위치를 만들 수 있습니다
이제 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;
}
이 매우 간단한 코드를 사용했습니다.
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
, 결과는 변경되지 않습니다.
그것은 나를 위해 일했습니다.
.vcontainer {
min-height: 10em;
display: table-cell;
vertical-align: middle;
}
.outer {
display: flex;
align-items: center;
justify-content: center;
}
내 친구의 기술 :
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;}
여기에 데모
블록 요소를 중앙에 배치하려면 (IE9 이상에서 작동) 래퍼가 필요합니다 div
.
.vcontainer {
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
}
모두 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>
이 공식을 사용하면 항상 균열없이 작동합니다.
#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>
거의 모든 메서드에서 높이를 지정해야하지만 종종 높이가 없습니다.
여기 높이를 알 필요가없는 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/
내 트릭은 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/
요소를 수직 및 수평으로 정렬하는 두 가지 방법이 있습니다.
- 부트 스트랩 4
- 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;
justify-content: 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>
기본적으로 h1은 블록 요소이며 첫 번째 img 다음 줄에 렌더링되며 두 번째 img가 블록 다음 줄에 나타납니다.
이 문제가 발생하지 않도록하려면 h1이 인라인 흐름 동작을 갖도록 설정할 수 있습니다.
#header > h1 { display: inline; }
div 내부 에 img를 절대적으로 배치하려면 포함 된 div를 "알려진 크기"로 설정해야 제대로 작동합니다. 내 경험상 기본 위치 속성을 변경해야합니다. 위치 : 상대는 나를 위해 작동합니다.
#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>
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/
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
합니다.
참고 : 계산 기능은 이전 브라우저와의 호환성 테스트를 거치지 않았습니다.
오늘에 따라 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%;
}
내 이해에 따라 요소를 포함하는 텍스트의 직계 부모는 높이가 있어야합니다. 당신도 도움이 되길 바랍니다. 감사!
div 내에서 단일 셀 테이블을 사용하십시오! 셀과 테이블 높이를 100 %로 설정하기 만하면 수직 정렬을 사용할 수 있습니다.
div 내부의 단일 셀 테이블은 수직 정렬을 처리하고 석기 시대까지 역 호환됩니다!
내가 가장 좋아하는 방법은 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 년 넘게 다음 솔루션 (위치 및 줄 높이 없음)을 사용해 왔으며 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>
이것은 div 내부의 i 요소에 대한 개인적인 솔루션입니다.
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;
}
저에게는 다음과 같이 작동했습니다.
<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"요소는 이제 외부 "div"내부에 수직으로 중앙에 배치됩니다.
# 상위 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>
디스플레이 플렉스를 사용하여 먼저 정렬하려는 항목의 컨테이너를 포장해야합니다.
<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;
}
딱 이것:
<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 내부의 단일 셀 테이블은 수직 정렬을 처리하고 석기 시대까지 역 호환됩니다!
<!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>
다음은 또 다른 (반응 형) 접근 방식입니다.
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/
저는 방금 웹 프로그래밍에 뛰어든 .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>
<div id="header" style="display: table-cell; vertical-align:middle;">
...
또는 CSS
.someClass
{
display: table-cell;
vertical-align:middle;
}
참고 URL : https://stackoverflow.com/questions/79461/how-to-vertical-align-elements-in-a-div
'IT박스' 카테고리의 다른 글
폴더가없는 경우 새로 만듭니다. (0) | 2020.10.02 |
---|---|
C와 C ++ 모두에서 유효한 코드가 각 언어로 컴파일 될 때 다른 동작을 생성 할 수 있습니까? (0) | 2020.10.02 |
Android 에뮬레이터에 APK 파일을 어떻게 설치합니까? (0) | 2020.09.30 |
모나드는 endofunctor 범주의 모노 이드 일뿐입니다. 무엇이 문제입니까? (0) | 2020.09.30 |
Chrome의 CSS 사용자 정의 스타일 버튼에서 파란색 테두리 제거 (0) | 2020.09.30 |