在容器 div 内定位地图框/传单地图

2022-01-12 00:00:00 mapbox leaflet css

我正在一个 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.

相关文章