programing tip

동적 너비 (CSS)가있는 중앙 고정 div

itbloger 2020. 10. 11. 09:14
반응형

동적 너비 (CSS)가있는 중앙 고정 div


이 CSS를 가질 div가 있습니다.

#some_kind_of_popup
{
    position: fixed;
    top: 100px;
    min-height: 300px;
    width: 90%;
    max-width: 900px;
}

이제이 div를 중앙에 배치하려면 어떻게해야합니까? 사용할 수 margin-left: -450px; left: 50%;있지만 화면이 900 픽셀 이상일 때만 작동합니다. 그 후 (윈도우가 900 픽셀 미만인 경우) 더 이상 중앙에 배치되지 않습니다.

나는 물론 어떤 종류의 js로 이것을 할 수 있지만 CSS로 이것을 수행하는 "더 정확"한 것이 있습니까?


fixed또는 absolute배치 된 요소 설정을 rightleft0, 배치 된 요소를 중앙에 배치 하는 것처럼 margin-left& 로 할 수 있습니다 .margin-rightautostatic

#example {
    position: fixed;
    /* center the element */
    right: 0;
    left: 0;
    margin-right: auto;
    margin-left: auto;
    /* give it dimensions */
    min-height: 10em;
    width: 90%;
}

이 바이올린에서 작업 하는 이 예제를 참조하십시오 .


다음은 CSS3의 transform속성을 안전하게 사용할 수있는 또 다른 방법입니다 .

.fixed-horizontal-center
{
    position: fixed;
    top: 100px; /* or whatever top you need */
    left: 50%;
    width: auto;
    -webkit-transform: translateX(-50%);
    -moz-transform: translateX(-50%);
    -ms-transform: translateX(-50%);
    -o-transform: translateX(-50%);
    transform: translateX(-50%);
}

... 또는 수평 및 수직 센터링을 모두 원하는 경우 :

.fixed-center
{
    position: fixed;
    top: 50%;
    left: 50%;
    width: auto;
    height: auto;
    -webkit-transform: translate(-50%,-50%);
    -moz-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    -o-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
}

<div id="container">
    <div id="some_kind_of_popup">
        center me
    </div>
</div>

You'd need to wrap it in a container. here's the css

#container{
    position: fixed;
    top: 100px;
    width: 100%;
    text-align: center;
}
#some_kind_of_popup{
    display:inline-block;
    width: 90%;
    max-width: 900px;  
    min-height: 300px;  
}

This works regardless of the size of its contents

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

source: https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

참고URL : https://stackoverflow.com/questions/17069435/center-fixed-div-with-dynamic-width-css

반응형