問題描述
我正在一個 Ruby on Rails 應用程序中使用 Mapbox.對于我的生活,我無法讓地圖遵守任何簡單的 CSS.唯一允許地圖出現的 CSS 是給它一個絕對位置,頂部和底部都為 0.改變高度和寬度以外的任何東西都會導致地圖消失.我想讓地圖在容器 div 內居中.代碼如下:
I am working with Mapbox in a Ruby on Rails app. For the life of me, I cannot get the map to adhere to any simple CSS. The only CSS that allows the map to appear is giving it an absolute position with a top and bottom of 0. Altering anything other than the height and width causes the map to disappear. I want to have the map centered inside a container div. Here is the code:
<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>
還有以下 CSS:
#map {
position: absolute;
top: 0;
bottom: 0;
height: 50%;
width: 50%;
}
如果我改變任何東西,地圖就會消失.我試圖給地圖容器 div 一個相對的位置.那是行不通的.我想要的只是將地圖包含在一個 div 中,這似乎并不難.2013年有一篇關于這個的帖子,但它已經過時了.感謝您的幫助.
If I change anything, the map disappears. I have tried to give the map-container div a position of relative. That does not work. All I want is for the map to be contained within a div, it doesn't seem like it should be difficult. There is one post about this from 2013 but it is outdated. Thanks for your help.
推薦答案
必須為 Leaflet 設置的唯一 css 規則(Mapbox 是 Leaflet) 元素定位靜態/相對時是絕對高度:
The only css rule that must be set for Leaflet's (Mapbox is an extended version of Leaflet) element when positioned static/relative is an absolute height:
#map {
height: 200px;
}
示例:http://plnkr.co/edit/vdeyLv?p=preview
這將始終有效,無論元素嵌套多深.如果未設置寬度,它將使用所有可用的寬度.當您想切換到以百分比設置高度時,您需要確保地圖元素的所有錨元素也都設置了高度:
That will work always, doesn't matter how deep the element is nested. When width is not set it will use all the width available. When you want to switch to setting height in percentages, you'll need to make sure that all the anchestor elements of the map element have a height set also:
#html, #body, #map-container {
height: 100%;
}
#map {
height: 40%;
}
示例:http://plnkr.co/edit/rAuNC0?p=preview
我猜想在 Mapbox 示例中使用絕對定位背后的原因是不必解釋上述內容,因為無論地圖元素嵌套多深,它都能正常工作.
I guess the reasoning behind using absolute positioning in the Mapbox examples is that one does not have to explain the above because no matter how deep you nest the map's element, it just works.
這篇關于在容器 div 內定位地圖框/傳單地圖的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!