your programing

너비 / 높이가 정의 된 div 콘텐츠의 중앙에 세로로 정렬하는 방법은 무엇입니까?

lovepro 2020. 10. 9. 11:34
반응형

너비 / 높이가 정의 된 div 콘텐츠의 중앙에 세로로 정렬하는 방법은 무엇입니까?


수직 정해진 너비 / 높이에서 콘텐츠를 중앙에 올바른 방법 하겠는가 div.

에는 높이가 다른 두 콘텐츠가 .content있습니다. 클래스를 사용하여 세로로 가운데에 두는 가장 좋은 방법은 무엇입니까 ? (그리고 모든 브라우저에서 작동하며의 솔루션없이 table-cell)

몇 가지 솔루션을 염두에두고 있지만 다른 아이디어를 알고 싶습니다 . 하나는 position:absolute; top:0; bottom: 0;margin auto.


나는 이것을 조금 조사했으며 네 가지 옵션이 있음을 발견했습니다.

버전 1 : 테이블 셀로 표시되는 상위 div

display:table-cell상위 div에서를 사용해도 괜찮다 면 다음 옵션을 사용할 수 있습니다.

.area{
    height: 100px;
    width: 100px;
    background: red;
    margin:10px;
    text-align: center;
    display:table-cell;
    vertical-align:middle;
}​

라이브 데모


버전 2 : 디스플레이 블록 및 콘텐츠 디스플레이 테이블 셀이있는 상위 div

.area{
    height: 100px;
    width: 100px;
    background: red;
    margin:10px;
    text-align: center;
    display:block;
}

.content {
    height: 100px;
    width: 100px;
    display:table-cell;
    vertical-align:middle;    
}​

라이브 데모


버전 3 : 상위 div 부동 및 콘텐츠 div를 디스플레이 테이블 셀로 사용

.area{
    background: red;
    margin:10px;
    text-align: center;
    display:block;
    float: left;
}

.content {
    display:table-cell;
    vertical-align:middle;
    height: 100px;
    width: 100px;
}​

라이브 데모


버전 4 : 절대 콘텐츠 위치가있는 상위 div 위치 상대

이 버전에서 내가 가진 유일한 문제는 모든 특정 구현에 대해 CSS를 만들어야한다는 것입니다. 그 이유는 콘텐츠 div가 텍스트를 채우는 높이를 설정해야하고 여백 상단이 그 높이를 파악해야하기 때문입니다. 이 문제는 데모에서 볼 수 있습니다. 콘텐츠 div의 높이 %를 변경하고 여기에 -.5를 곱하여 모든 시나리오에서 수동으로 작동하도록 할 수 있습니다.

.area{
    position:relative; 
    display:block;
    height:100px;
    width:100px;
    border:1px solid black;
    background:red;
    margin:10px;
}

.content { 
    position:absolute;
    top:50%; 
    height:50%; 
    width:100px;
    margin-top:-25%;
    text-align:center;
}​

라이브 데모


이것은 display: flex단 몇 줄의 코드로 도 수행 할 수 있습니다 . 다음은 예입니다.

.container {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
}

라이브 데모


기사 에서이 해결책을 찾았습니다.

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

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

It work like a charm if the height of element is not fixed.


margin: all_four_margin

by providing 50% to all_four_margin will place the element at the center

style="margin: 50%"

you can apply it for following too

margin: top right bottom left

margin: top right&left bottom

margin: top&bottom right&left

by giving appropriate % we get the element wherever we want.

참고URL : https://stackoverflow.com/questions/10968726/how-to-vertically-align-into-the-center-of-the-content-of-a-div-with-defined-wid

반응형