"위치: 절대" 요소의 중심을 잡는 방법
속성을 가진 요소의 중심을 잡는 데 문제가 있습니다.position로 설정한.absolute이미지가 중심에 맞지 않는 이유를 아는 사람이 있습니까?
body {
text-align: center;
}
#slideshowWrapper {
margin-top: 50px;
text-align: center;
}
ul#slideshow {
list-style: none;
position: relative;
margin: auto;
}
ul#slideshow li {
position: absolute;
}
ul#slideshow li img {
border: 1px solid #ccc;
padding: 4px;
height: 450px;
}
<body>
<div id="slideshowWrapper">
<ul id="slideshow">
<li><img src="https://source.unsplash.com/random/300*300?technology" alt="Dummy 1" /></li>
<li><img src="https://source.unsplash.com/random/301*301?technology" alt="Dummy 2" /></li>
</ul>
</div>
</body>
너비를 설정한 경우 다음을 사용할 수 있습니다.
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
text-align: center;
모르는 사이에width/height배치된1 요소 중에서 다음과 같이 정렬할 수 있습니다.
.child {
position: absolute;
top: 50%; /* position the top edge of the element at the middle of the parent */
left: 50%; /* position the left edge of the element at the middle of the parent */
transform: translate(-50%, -50%); /* This is a shorthand of
translateX(-50%) and translateY(-50%) */
}
CSS Transform은 IE9 이상에서 지원된다는 점에 주목할 필요가 있습니다. (간단히 설명하기 위해 벤더 접두사 생략)
설명.
추가 /left 추가50%요소의 상단/왼쪽 여백 가장자리를 부모의 중간으로 이동하고, (음) 값으로 함수를 수행합니다.-50%요소를 해당 크기의 절반만큼 이동합니다.따라서 요소는 중앙에 배치됩니다.
이는 /properties의 left백분율 값이 포함 블록을 만드는 상위 요소의 높이/폭에 상대적이기 때문입니다.
변환 함수의 백분율 값은 요소 자체의 너비/높이에 상대적이지만(실제로는 경계 상자의 크기를 나타냅니다).
단방향 정렬의 경우 다음과 같이 하십시오.translateX(-50%)또는translateY(-50%)대신.
있는 원소position static를 들어, 예를 들면.relative,absolute,fixed가치.
을 잡는 것.absoluteLypositioned(" CSS")는 CSS입니다.
ul#slideshow li {
position: absolute;
left:50%;
margin-left:-20px;
}
margin-left중심을 맞추려는 요소 너비의 절반(음)까지.
수직 및 수평으로 정렬된 중심
top: 0;
bottom: 0;
margin: auto;
position: absolute;
left: 0;
right: 0;
참고: 요소에는 설정할 폭과 높이가 있어야 합니다.
절대 요소의 중심을 맞추려면
#div {
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
width:300px; /* Assign a value */
height:500px; /* Assign a value */
margin:auto;
}
컨테이너를 왼쪽에서 오른쪽으로 중앙에 배치하고 위쪽에서 아래쪽으로 배치하지 않으려면
#div {
position:absolute;
left:0;
right:0;
width:300px; /* Assign a value */
height:500px; /* Assign a value */
margin:auto;
}
컨테이너를 왼쪽에서 오른쪽으로 구분하지 않고 위에서 아래로 중앙에 배치하려는 경우
#div {
position:absolute;
top:0;
bottom:0;
width:300px; /* Assign a value */
height:500px; /* Assign a value */
margin:auto;
}
2015년 12월 15일 기준 업데이트
저는 이것을 몇 달 전에 또 다른 새로운 속임수를 배웠습니다.상대적인 상위 요소가 있다고 가정합니다.
여기 당신의 절대적인 요소가 있습니다.
.absolute-element {
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
width:50%; /* You can specify ANY width values here */
}
이것으로, 저는 그것이 저의 예전 해결책보다 더 나은 답이라고 생각합니다.너비와 높이를 지정할 필요가 없기 때문입니다.이것은 요소 자체의 내용을 조정합니다.
2021년 4월 23일 기준 업데이트
인 해결책을 의적인위않 OP지만는답하지, 만인해을원다면있, 니습한이이것다결책대, 에라는 것이 .flexbox예가 .여기 예가 있어요.
#parent {
display:flex;
align-items:center;
justify-content:center;
}
가 컨이너가다변환다니됩로음으로 입니다.flex그리고 수평으로 중앙에 어린이 항목을 정렬하는 것은 사용하는 것입니다.justify-content:center그리고 수직은 사용하는 것입니다.align-items:center최신 브라우저도 지원하므로 안전하게 사용할 수 있습니다.
그러나 먼저 Flexbox가 작동하는 방법을 읽어보십시오.
https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox
Flexbox 지원 브라우저
간단한 CSS 트릭, 다음을 추가합니다.
width: 100%;
text-align: center;
이미지와 텍스트 모두에서 작동합니다.
이것은 저에게 효과가 있었습니다.
position: absolute;
left: 50%;
transform: translateX(-50%);
"위치: 절대" 요소의 중심을 맞춥니다.
.your-element {
position: absolute;
left: 0;
right: 0;
text-align: center; // or this -> margin: 0 auto;
}
위치의 중심을 잡으려면: 절대 속성을 설정해야 합니다. 왼쪽: 50% 및 왼쪽: div 너비의 -50%.
<!-- for horizontal -->
<style>
div.center{
width:200px;
left:50%;
margin-left:-100px;
position:absolute;
}
</style>
<body>
<div class='center'>
should be centered horizontaly
</div>
</body>
수직 중심 절대값의 경우 상단만 왼쪽이 아닌 동일한 작업을 수행해야 합니다. (참고: html 및 본문은 최소 높이 100%여야 합니다; )
<!-- for vertical -->
<style>
body,html{
min-height:100%;
}
div.center{
height:200px;
top:50%;
margin-top:-100px;
position:absolute;
}
</style>
<body>
<div class='center'>
should be centered verticaly
</div>
</body>
그리고 둘 다에 대해 결합될 수 있습니다.
<!-- for both -->
<style>
body,html{
min-height:100%;
}
div.center{
width:200px;
height:50px
left:50%;
top:50%;
margin-left:-100px;
margin-top:-25px;
position:absolute;
}
</style>
<body>
<div class='center'>
should be centered
</div>
</body>
또는 이제 절대 위치의 플렉스 박스를 사용할 수 있습니다.
.parent {
position: relative;
display: flex;
justify-content: center;
}
.child {
position: absolute;
}
<div class="centered_content"> content </div>
<style type="text/css">
.centered_content {
text-align: center;
position: absolute;
left: 0;
right: 0;
}
</style>
데모 보기: http://jsfiddle.net/MohammadDayeh/HrZLC/
text-align: center를 사용하여 작업position: absolute추가시요소를 추가할 left: 0; right: 0;
변환 특성을 사용할 수 있습니다.
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
단순할수록 최고입니다.
img {
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto auto;
position: absolute;
}
그런 다음 img 태그를 스포츠 위치인 상대 속성 태그에 다음과 같이 삽입해야 합니다.
<div style="width:256px; height: 256px; position:relative;">
<img src="photo.jpg"/>
</div>
요소의 너비를 모르는 경우 다음 코드를 사용할 수 있습니다.
<body>
<div style="position: absolute; left: 50%;">
<div style="position: relative; left: -50%; border: dotted red 1px;">
I am some centered shrink-to-fit content! <br />
tum te tum
</div>
</div>
fiddle에서의 데모: http://jsfiddle.net/wrh7a21r/
출처: https://stackoverflow.com/a/1777282/1136132
아마도 가장 짧은
position:absolute;
left:0;right:0;top:0;bottom:0;
margin:0 auto;
다른 많은 사람들이 말했듯이 ⬇️
.element {
position: absolute;
left: 0;
top: 0;
transform: translate(-50%, -50%);
}
작동해야 합니다.그러나 .element는 위치가 relative인 래퍼에 있어야 합니다. (전체 HTML 페이지의 중앙에 만들고 싶지 않은 경우)
참고로 저는 CSS 센터링을 위한 의사 라이브러리를 만들었습니다.나는 그것이 나의 dev 후배들을 위해 필요했습니다.그러니, 자유롭게 확인해 보세요.http://dev.solcode.net/centercss/
용사를 합니다.left: calc(50% - Wpx/2);여기서 W는 제게 맞는 원소의 폭입니다.
당신이 무엇을 성취하고 싶은지 잘 모르겠지만, 이 경우에는 단지 추가하는 것.width: 100%;의 신에게에.ul#slideshow li할 수 있을 겁니다
설명.
그img태그는 인라인 블록 요소입니다.즉, 텍스트처럼 인라인으로 흐르지만 블록 요소처럼 너비와 높이가 있습니다.에는 두 개의 CSS가 .text-align: center;에 <body> 리고에그까지.#slideshowWrapperbtw입니다) 모든 및 요소에 을 맞춥니다. 과 같은 요소가 있습니다. 당신의 코드에서 이것들은li태그입니다. 모든 블록 요소가width: 100%정적 흐름인 경우(position: static;), 기본값입니다.문제는 당신이 말할 때li될 꼬리표position: absolute;당신은 그들을 정상적인 정적 흐름에서 벗어나게 하고, 이것은 그들이 그들의 내부 내용에 맞추기 위해 그들의 크기를 축소하게 합니다, 다시 말해서 그들은 일종의 "잃어버린" 것입니다.width: 100%소유물.
목록 항목이 중심에 있지 않기 때문에 이미지가 중심에 있지 않고 텍스트만 중심에 있습니다.전체 목록의 중심을 맞추거나 목록 내 영상의 중심을 맞추면 원하는 위치를 지정할 수 있습니다.
코드의 수정된 버전은 하단에서 찾을 수 있습니다.내 개정판에서는 목록과 그 안에 있는 이미지를 모두 중앙에 배치합니다.
진실은 절대로 설정된 위치를 가진 요소의 중심을 잡을 수 없다는 것입니다.
하지만 이 행동은 모방될 수 있습니다!
참고: 이 지침은 img뿐만 아니라 모든 DOM 블록 요소에서 작동합니다.
이미지를 div 또는 다른 태그(ali의 경우)로 둘러쌉니다.
<div class="absolute-div"> <img alt="my-image" src="#"> </div>참고: 이러한 요소에 지정된 이름은 특별하지 않습니다.
CSS나 scss를 변경하여 div에 절대적인 위치를 지정하고 이미지를 중심에 맞춥니다.
.absolute-div { position: absolute; width: 100%; // Range to be centered over. // If this element's parent is the body then 100% = the window's width // Note: You can apply additional top/bottom and left/right attributes // i.e. - top: 200px; left: 200px; // Test for desired positioning. } .absolute-div img { width: 500px; // Note: Setting a width is crucial for margin: auto to work. margin: 0 auto; }
그리고 여기 있습니다!img가 중심이 되어야 합니다!
코드:
사용해 보십시오.
body
{
text-align : center;
}
#slideshow
{
list-style : none;
width : 800px;
// alter to taste
margin : 50px auto 0;
}
#slideshow li
{
position : absolute;
}
#slideshow img
{
border : 1px solid #CCC;
padding : 4px;
height : 500px;
width : auto;
// This sets the width relative to your set height.
// Setting a width is required for the margin auto attribute below.
margin : 0 auto;
}
<ul id="slideshow">
<li><img src="http://lorempixel.com/500/500/nature/" alt="Dummy 1" /></li>
<li><img src="http://lorempixel.com/500/500/nature/" alt="Dummy 2" /></li>
</ul>
이것이 도움이 되었기를 바랍니다.행운을 빕니다.
상대 개체 내부의 절대 개체는 상위 개체에 상대적입니다. 여기서 문제는 컨테이너에 대한 정적 너비가 필요하다는 것입니다.#slideshowWrapper 사용자가 것과 .
body {
text-align: center;
}
#slideshowWrapper {
margin-top: 50px;
text-align:center;
width: 500px;
}
ul#slideshow {
list-style: none;
position: relative;
margin: auto;
}
ul#slideshow li {
position: relative;
left: 50%;
}
ul#slideshow li img {
border: 1px solid #ccc;
padding: 4px;
height: 450px;
}
다음은 "위치: 절대"의 중심 요소에 대한 쉽고 최상의 솔루션입니다.
body,html{
min-height:100%;
}
div.center{
width:200px;
left:50%;
margin-left:-100px;/*this is 50% value for width of the element*/
position:absolute;
background:#ddd;
border:1px solid #999;
height:100px;
text-align:center
}
<style>
</style>
<body>
<div class='center'>
should be centered verticaly
</div>
</body>
그냥 사용하기display: flex그리고.justify-content: center에.
body {
text-align: center;
}
#slideshowWrapper {
margin-top: 50px;
text-align: center;
}
ul#slideshow {
list-style: none;
position: relative;
margin: auto;
display: flex;
justify-content: center;
}
ul#slideshow li {
position: absolute;
}
ul#slideshow li img {
border: 1px solid #ccc;
padding: 4px;
height: 100px;
}
<body>
<div id="slideshowWrapper">
<ul id="slideshow">
<li><img src="https://source.unsplash.com/random/300*300?technology" alt="Dummy 1" /></li>
<li><img src="https://source.unsplash.com/random/301*301?technology" alt="Dummy 2" /></li>
</ul>
</div>
</body>
<!-- Images from Unsplash-->
이 솔루션은 JSFIDDLE에서 찾을 수 있습니다.
다음 방법을 사용할 수 있습니다.
* { margin: 0px; padding: 0px; }
#body { height: 100vh; width: 100vw; position: relative;
text-align: center;
background-image: url('https://s-media-cache-ak0.pinimg.com/originals/96/2d/ff/962dff2247ad680c542622e20f44a645.jpg');
background-size: cover; background-repeat: no-repeat; }
.text { position: absolute; top: 0; bottom: 0; left: 0; right: 0; height:100px;
display: inline-block; margin: auto; z-index: 999999; }
<html>
<body>
<div id="body" class="container-fluid">
<!--Background-->
<!--Text-->
<div class="text">
<p>Random</p>
</div>
</div>
</body>
</html>
1- 절대 위치 요소의 폭을 알고 있는 경우.
width: 200px;
position: absolute;
left: 50%;
margin-left: -100px
2- 절대 위치 요소의 폭을 모를 때.응답성은 뛰어나지만 CSS3 이전 브라우저에는 문제가 있을 수 있습니다.
position: absolute;
left: 50%;
-webkit-transform: translateX(-50%);
transform: translateX(-50%)
3- 절대 위치 요소의 폭을 알 수 없지만 설계에 적합하지 않을 수 있는 요소의 부모 폭을 100% 넓힙니다.
position: absolute;
left: 0;
right: 0;
margin: auto
너비를 알고 있는 경우 세 번째 옵션도 사용할 수 있습니다. 그러면 가운데로 이동합니다.
요소 또는 요소 그룹의 중심을 절대적으로 조정하는 가장 좋아하는 방법은 컨테이너를 절대적으로 배치하고 상대적인 컨테이너의 높이와 너비로 만든 다음 유연성을 사용하여 요소를 내부에 정렬하는 것입니다.
이 특정한 경우:
body {
position: relative; /* OPTIONAL */
}
#slideshowWrapper {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
flex-direction: row; /* OPTIONAL IF ONLY ONE ELEMENT */
justify-content: center;
align-items: center;
}
도움이 되길 바랍니다, 건배.
이 경우 아래와 같은 코드로 충분하다고 생각합니다.
ul#slideshow li {
position: absolute;
left: 0;
right: 0;
}
#parent
{
position : relative;
height: 0;
overflow: hidden;
padding-bottom: 56.25% /* images with aspect ratio: 16:9 */
}
img
{
height: auto!important;
width: auto!important;
min-height: 100%;
min-width: 100%;
position: absolute;
display: block;
/* */
top: -9999px;
bottom: -9999px;
left: -9999px;
right: -9999px;
margin: auto;
}
위에 나열된 센터링 방법을 어디서 봤는지 기억이 안 나요, 음의 상단, 오른쪽, 하단, 왼쪽 값을 사용합니다.저는 대부분의 상황에서 이 테크닉이 최고입니다.
위의 조합을 사용하면 이미지가 다음 설정을 사용하여 배경 이미지처럼 작동합니다.
background-position: 50% 50%;
background-repeat: no-repeat;
background-size: cover;
번째 더 내용은여기에서 수 : 번째예제대한자내다용수확있다습니인첫할서음에은세한.
CSS를 사용하여합니다.
Position absolute(위치 절대)는 흐름에서 이를 꺼내어 0x0으로 상위 요소에 배치합니다(마지막 블록 요소는 위치 절대 또는 위치 상대).
당신이 무엇을 성취하려고 하는지 정확히 모르겠습니다. 리를 a로 설정하는 것이 가장 좋을 수도 있습니다.position:relative그리고 그것이 그들을 집중시킬 것입니다.의 현재 CSS가 주어지면 CSS가 주어집니다.
http://jsfiddle.net/rtgibbons/ejRTU/ 에서 게임을 해보세요.
현재 일어나고 있는 것처럼 보이는 것은 두 가지 해결책이 있다는 것입니다. 마진을 중심으로 하는 것과 위치를 중심으로 하는 것입니다.둘 다 정상적으로 작동하지만 이 중심 요소를 기준으로 요소를 절대적으로 배치하려면 두 번째 요소의 절대 위치가 배치된 첫 번째 부모로 기본 설정되므로 절대 위치 방법을 사용해야 합니다.이와 같은 경우:
<!-- CENTERED USING MARGIN -->
<div style="width:300px; height:100px; border: 1px solid #000; margin:20px auto; text- align:center;">
<p style="line-height:4;">width: 300 px; margin: 0 auto</p>
<div style="position:absolute; width:100px; height:100px; background-color:#ff0000; top:-20px; left:0px;">
<p style="line-height:4;">Absolute</p>
</div>
</div>
<!-- CENTERED USING POSITION -->
<div style="position:absolute; left:50%; width:300px; height:100px; border: 1px solid #000; margin:20px 0 20px -150px; text-align:center;">
<p style="line-height:2;">width:300px; position: absolute; left: 50%; margin-left:-150px;</p>
<div style="position:absolute; width:100px; height:100px; background-color:#ff0000; top:0px; left:-105px;">
<p style="line-height:4;">Absolute</p>
</div>
</div>
제가 이 게시물을 읽기 전까지 마진:0 자동 기술을 사용하여 제 컨텐츠의 왼쪽에 메뉴를 만들기 위해 오른쪽에 같은 너비의 열을 만들어야 했습니다.안이쁘다.감사합니다!
사용하다margin-left: x%;여기서 x는 요소 폭의 절반입니다.
언급URL : https://stackoverflow.com/questions/8508275/how-to-center-a-position-absolute-element
'programing' 카테고리의 다른 글
| bash 및 regex를 사용하여 한 줄에서 프로세스 찾기 및 종료 (0) | 2023.05.02 |
|---|---|
| Xcode 9.3, .xcworkspace/xcshareddata/IDEWorkspaceChecks.plist에서 새로 생성된 파일을 커밋해야 합니까? (0) | 2023.05.02 |
| SQL Server 2008 Management Studio에서 텍스트 또는 막대(MAX) 열의 전체 내용을 보려면 어떻게 합니까? (0) | 2023.04.27 |
| Bash의 조건부로 "아무것도 하지 않음"을 의미하는 명령어는 무엇입니까? (0) | 2023.04.27 |
| MVC 5 액세스 클레임 ID 사용자 데이터 (0) | 2023.04.27 |
