我无法获得div元素的中心位置。请问你能帮帮我吗?我需要我的div也会在移动设备上做出响应。我的代码
'
<div id="owl-demo" class="owl-carousel">
<div class="item"><img src="images/quote.png"/><br/> TEST TEST TEST TEST TEST TEST</div>
<div class="item"><img src="images/quote.png"/><br/> TEST TEST TESTTEST TEST TESTTEST TEST TEST</div>
<div class="item"><img src="images/quote.png"/><br/> TEST TEST TESTTEST TEST TESTTEST TEST TEST</div>
</div>
</div>'
`#owl-demo .item {
background: #fff;
padding: 20px 10px;
margin: 5px;
color: #333;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
text-align: center;
}
#owl-demo{
margin-left: auto;
margin-right: auto;
width:100%;
}`
答案 0 :(得分:0)
如果您将position:relative;
放在父母身上,那么请放在儿童身上(即#owl-demo
):
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
无论如何都是垂直和水平的。
另一种方式是flexbox:
.mainflex {
display:flex;
justify-content:center;
align-items:center;
height:100vh;
width: 100vw;
}
.mainflex
只是父元素,不需要调整子元素。大卫提醒我,如果你不希望他们并排添加flex-direction: column;
。
html,body {
height:100%;
width:100%;
position:relative;
}
#owl-demo .item {
background: #fff;
padding: 20px 10px;
margin: 5px;
color: #333;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
text-align: center;
}
#owl-demo {
position: absolute;
top:50%;
left: 50%;
transform:translate(-50%,-50%);
margin-left: auto;
margin-right: auto;
width: 100%;
}
`
<div id="owl-demo" class="owl-carousel">
<div class="item">
<img src="http://placehold.it/350x150/000/fff?text=1" />
<br/>TEST TEST TEST TEST TEST TEST</div>
<div class="item">
<img src="http://placehold.it/350x150/000/fff?text=2" />
<br/>TEST TEST TESTTEST TEST TESTTEST TEST TEST</div>
<div class="item">
<img src="http://placehold.it/350x150/000/fff?text=3" />
<br/>TEST TEST TESTTEST TEST TESTTEST TEST TEST</div>
</div>
htmal,
body {
height: 100%;
width: 100%;
background: black;
}
#mainFlex {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100vw;
height: 100vh;
}
.child {
width: 50px;
height: 50px;
border-radius: 50%;
background: yellow;
}
<main id='mainFlex'>
<div class='child'></div>
<div class='child'></div>
</main>