Joh*_*ess 4 css leaflet mapbox
我在Ruby on Rails应用程序中使用Mapbox.对于我的生活,我无法让地图坚持任何简单的CSS.允许地图出现的唯一CSS是给它一个顶部和底部为0的绝对位置.更改高度和宽度以外的任何内容都会导致地图消失.我想让地图集中在容器div中.这是代码:
<div id="map-container">
<div id='map'>
</div>
</div>
<script>
L.mapbox.accessToken = 'pk.eyJ1IjoiYWxvb2thdG9tbW9yb3ciLCJhIjoiNGM4ODhkZjUwMGM1ZDE4M2VjNzQ4MmQ4ODcxMjk5ZjMifQ.XVvFc8kl-0z4NAblE-mNqw';
var map = L.mapbox.map('map', 'mapbox.streets').setView([40, -74.50], 10);
</script>
Run Code Online (Sandbox Code Playgroud)
以下CSS:
#map {
position: absolute;
top: 0;
bottom: 0;
height: 50%;
width: 50%;
}
Run Code Online (Sandbox Code Playgroud)
如果我改变了什么,地图就会消失.我试图给map-container div一个相对位置.这不起作用.我想要的只是将地图包含在div中,看起来似乎并不困难.从2013年开始有一篇关于此的帖子,但它已经过时了.谢谢你的帮助.
的唯一的CSS规则必须为单张的设置(Mapbox是一个扩展版本单张)元件定位静态时/相对是绝对高度:
#map {
height: 200px;
}
Run Code Online (Sandbox Code Playgroud)
示例:http://plnkr.co/edit/vdeyLv?p = preview
这将始终有效,无论嵌套元素的深度如何.如果未设置宽度,则将使用所有可用宽度.当您想要以百分比切换到设置高度时,您需要确保地图元素的所有anchestor元素也具有高度设置:
#html, #body, #map-container {
height: 100%;
}
#map {
height: 40%;
}
Run Code Online (Sandbox Code Playgroud)
示例:http://plnkr.co/edit/rAuNC0?p = preview
我想在Mapbox示例中使用绝对定位背后的原因是,人们无需解释上述内容,因为无论您对地图元素的嵌套程度有多深,它都能正常工作.
只需将两个 div 的 'position:absolute' 更改为 'position:relative' 即可:
<div id="map-container">
<div id="map">
</div>
</div>
#map-container {
position: relative;
height: 180px;
width: 600px;
}
#map {
position: relative;
height: inherit;
width: inherit;
}
Run Code Online (Sandbox Code Playgroud)
注意:“#map”元素的高度和宽度将由父 div“#map-container”继承,在本例中或您设置的任何内容中,其分别为“180px”和“600px”。
演示:http://plnkr.co/edit/qjIAiud3aUF11iQPDKj0 ?p=preview