Aaron Beaudoin
Aaron Beaudoin

Reputation: 1147

How do I size an electron window's width based on the width of an HTML element inside it?

I have an element in the HTML of the electron window and I don't know how wide the element will be. How can I set the minimum width of the electron BrowserWindow which was created in main.js to be equal to the width of said HTML element?

I tried using element.offsetWidth in the index.html file to get the element's width and then using the below code in the same file to set the window's minimum size, but the size ended up being off somehow. I don't know why. It seems from some console output that it should be working.

var remote = require('electron').remote;
var win = remote.getCurrentWindow();
win.setMinimumSize(elementWidth, 400);

My guess is that my screen's pixel are not the same size as the CSS pixels, but I'm not really sure. Is there just a better way to do this altogether or am I missing something?

Upvotes: 3

Views: 4725

Answers (1)

Just a student
Just a student

Reputation: 11020

It sounds to me like the window borders (and scrollbar, for example) are not taken into account. You can take those into account by first setting the size you want, then reading the actual size you have and updating the size to what you want plus the difference you detected.

// get elementWidth in some way
var remote = require('electron').remote,
    win = remote.getCurrentWindow();
win.setMinimumSize(elementWidth, 400);
// check size, update window width
var contentWidth = window.innerWidth;
if (contentWidth !== elementWidth) {
  win.setMinimumSize(2 * elementWidth - contentWidth, 400);
}

Alternatively, you can use the win.setContentSize method directly, which should achieve what you want (although it does not enforce a minimum size, obviously...

// get elementWidth in some way
var remote = require('electron').remote,
    win = remote.getCurrentWindow();
win.setContentSize(elementWidth, 400);

Upvotes: 1

Related Questions