What is the best way to apply css styles to buttons in Leaflet?

Trying to customize the CSS for the zoom buttons in Leaflet, but unable to assign a class or id. How can I access them?

Any suggestions?

Thanks!

Map declaration:

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
    attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
    maxZoom: 18,
    id: 'mapbox.streets',
    accessToken: 'pk.eyJ1IjoicHcxN2wwMDgiLCJhIjoiY2pua2c2OWxuMGVkOTNxbWh5MWNqajEwdyJ9.X_SuGwNGs12TwCsrsUvBxw'
}).addTo(map);

Adding the zoom feature:

L.control.zoom({
    position: 'topright',
}).addTo(map);

Upon page load, zoom button appears with Leaflet classes. How can I make custom changes to them?

Answer №1

To customize the appearance of the zoom buttons, you can modify the built-in CSS selectors in the following way:

.leaflet-touch .leaflet-bar a {
  width: 50px;
  background-color: blue;
}
var map = L.map('mapid').setView([51.505, -0.09], 13);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

L.marker([51.5, -0.09]).addTo(map)
  .bindPopup('A customizable popup with CSS3.<br> Easy to style.')
  .openPopup();
#mapid {
  height: 180px;
}

.leaflet-touch .leaflet-bar a {
  width: 50px;
  background-color: blue;
}

body {
  margin: 0px;
}
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e626b6f68626b7a4554352f352b">[email protected]</a>/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin="" />
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="213da43f39393c39323304797b727770"},"|g|r":"","format_args":[],"remove_css_class":[""],"css_classes":"atomic_group"},{"start":202,"end":222,"attributes":{"format_args":[],"annotation":""},"value":"[{\"text\":\" Easily customizable.\"}]"}]' tabindex="0" data-permitted-grammar="true">[email protected]</a>/dist/leaflet.js" integrity="sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg==" crossorigin=""></script>

<div id="mapid"></div>

Alternatively, you can achieve this using JavaScript:

document.getElementsByClassName("leaflet-control-zoom-out")[0].style.setProperty('width', '50px');

document.getElementsByClassName("leaflet-control-zoom-out")[0].style.setProperty('background-color', 'blue');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to enhance the appearance of a TextField in JavaFX to resemble the sleek design of Android or material UI?

Is there a way to create a window like this in JavaFX? Take a look at the textfield shown in the image below... I recently came across the Jphonex framework that allows for this type of display. However, when I package it into a Jar file and try to run it ...

Framer Motion: Embrace the End of Animation Looping

Seeking help in creating a looped animation using the Framer Motion library with a slight delay. The animation plays upon mounting and webpage refresh but does not repeat as desired. Have reviewed the documentation but struggling with the syntax. const An ...

Delayed execution not completely cancelled prior to component being unmounted

Alert: Avoid calling setState (or forceUpdate) on an unmounted component. While this won't cause any issues, it could suggest a memory problem in your application. Make sure to clean up all subscriptions and async tasks in the componentWillUnmount met ...

showing javascript strings on separate lines

I need assistance with displaying an array value in a frontend Angular application. How can I insert spaces between strings and show them on two separate lines? x: any = [] x[{info: "test" + ',' + "tested"}] // Instead of showing test , teste ...

Deactivating checkboxes once the maximum selection has been made through jquery

I need assistance with my jQuery code that is supposed to disable checkboxes in a multidimensional array after reaching the maximum number of selections. However, I am having trouble identifying the issue within the code. Any guidance would be greatly ap ...

How can I position a div column-10 to the right and make it stay fixed in place

I'm having an issue trying to position a div on the right side without causing content to overlap with the navbar. I've attempted using `position:absolute top:0 right:0`, but it's not working as intended. <link href="https:// ...

Maintain the values of radio buttons, dropdowns, and checkboxes using Javascript

When I click on a radio button, it activates a drop down menu. Upon selecting different values from the drop down, various checkboxes become visible. Now, I want to preserve the selection of the radio button along with the selected drop down values and ch ...

Enhance user experience with JQUERY - MouseEnter, Focus, Hover, and Blur

Here is the current code snippet for showing and hiding a footer banner. Everything seems to be working fine except for an issue with MouseOver functionality. The MouseOver feature works as expected, but when a user clicks within the area, the highlight d ...

The query for Node.js using mysql is not defined

Recently, I've been working with Node.js and attempting to incorporate mysql in conjunction with nodejs. Specifically, I have written a query trying to retrieve numbers from a table: select numbers from TABLE, but the end result shows up as: "undef ...

Display the URL with proper formatting in the print function

I am trying to create a table with clickable URLs in a "Link" column, but the URLs are too long and I want to show a custom title instead. So far, I have used the following code: str = "Test Title"; link = str.link("https://my_long_url.com/v1.0/ui/index. ...

The function setCustomValidity() will continue to display even after the form has been successfully filled out

My form is very simple and I am trying to validate it using the required attribute: <form name="form"> <label for="Header">Title</label> <input type="text" class="span5" name="Header" ng-model="Message.header" placeholder="Title" on ...

flexbox: Two vertical icons tightly aligned without any space

Hey everyone, I've been working on this layout: https://i.sstatic.net/4Aye0.png Here's what I tried so far: Resetting padding and margin in the <a href> and in the <img src...> HTML container <div> <div className="pe ...

The length of a string in JavaScript is not the same as the len() function

Picture this scenario: when you type the following text into an HTML textarea: 123456 7 Using JavaScript to calculate the length of this text with string.length results in 10. However, if you measure the length of the same input in Python with l ...

Transform a text node into an HTML element with the help of JQuery

Consider this HTML snippet: <div> Lorem ipsum <span>dolor sit</span> amet <span>consectetur adipiscing elit</span> eiusmod tempor </div> To select the text nodes [Lorem ipsum, amet, eiusmod tempor], ...

I am looking to update my dexie values from null to empty strings

I am facing an issue where the data-table values with null entries need to be replaced with empty strings. There are instances when the department value is empty, resulting in null entries in the data tables. db = db_open(); db.fuel.toArray().then(fuel = ...

Which is the better option for selecting DOM elements in a Vuejs 3 application: using raw js or jquery?

 I am currently working on developing an application using Node.js and Vue.js 3. One of the features I have implemented is a sidebar that dynamically fetches links from a routes file and displays them. The sidebar consists of a component that organize ...

Issue with setting GeoJSON in jQuery callback using Mapbox`

Using Jquery, I am trying to retrieve geojson points data (which will set markers on a map) from a database. function remm(id){ $.ajax({ type: "POST", url:"geojson2.php", data:{ u_id:id[0], t_id:id[2] }, success: functi ...

Navigate to a PDF file from an HTML5 application using PhoneGap by accessing an external link

Can anyone help me figure out what I'm doing wrong here? Essentially, I am trying to open a PDF in Google Viewer: <a id="pdflink" href="https://docs.google.com/viewer?url=http://pdpdpd.pdf" target="_blank">Pdf</a> When it opens in the vi ...

Attempting to establish a connection with MongoDB through Realm

Exploring Realm and MongoDB for the first time has been an interesting journey for me. I began by following a helpful tutorial as a starting point for my project. Here is the link to my project structure on CodeSandbox The folder structure includes: src ...

Processing user inputs, comparing them with JSON data, and displaying the corresponding results using JavaScript

I am currently developing a JavaScript form where users are asked to select their gender (radio button) and occupation (dropdown). Gender: <p> Pick Your Gender:</p> Male <input type="radio" id="gender_male" name="gender" value="male"/> ...