- Style width Property
- Поддержка браузеров
- Синтаксис
- Технические подробности
- Еще примеры
- пример
- пример
- пример
- Style css width javascript
- # Set the Width and Height of an Element using JavaScript
- # Setting width and height has no effect on inline elements
- # Setting the element’s display to inline-block
- # Set the Width and Height on a Collection of Elements
- # Additional Resources
- Javascript Reference — HTML DOM Style width Property
- Browser Support
- Syntax
- Property Values
- Technical Details
- Example
- Example 3
- Example 4
Style width Property
Ширина свойство устанавливает или возвращает ширину элемента.
Ширина свойство имеет эффект только на блочных элементах или на элементах с абсолютным или фиксированным положением. Переполняющее содержимое можно манипулировать с помощью свойства переполнения.
Совет: Используйте высоту свойства , чтобы установить или вернуть высоту элемента.
Поддержка браузеров
Ширина свойство поддерживается во всех основных браузерах.
Синтаксис
Возвращает свойство ширины:
Установите свойство ширины:
Стоимость | Описание |
---|---|
auto | Браузер устанавливает ширину. Это по умолчанию |
length | Определяет ширину в единицах длины |
% | Определяет ширину в% от родительского элемента |
initial | Установка этого свойства в значение по умолчанию. Читайте о первоначальном |
inherit | Inherits это свойство от родительского элемента. Читайте о унаследовать |
Технические подробности
Значение по умолчанию: | авто |
---|---|
Возвращаемое значение: | Строка, представляющая ширину элемента |
CSS версия | CSS1 |
Еще примеры
пример
пример
Измените высоту и ширину элемента:
document.getElementById(«myImg»).style.height = «300px»;
document.getElementById(«myImg»).style.width = «300px»;
пример
Возвращает ширину элемента:
Style css width javascript
Last updated: Jan 11, 2023
Reading time · 3 min
# Set the Width and Height of an Element using JavaScript
Use the style.width and style.height properties to set the width and height of an element, e.g. box.style.width = ‘100px’ .
The width and height properties set the element’s width and height to the supplied values.
Here is the HTML for the examples.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> div id="box" style="background-color: salmon">Box 1div> script src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!const box = document.getElementById('box'); // ✅ Set width to 100px box.style.width = '100px'; // ✅ Set height to 100px box.style.height = '100px';
The style object allows us to set, read or update any CSS property on the element.
Copied!const box = document.getElementById('box'); // ✅ Set width to 100px box.style.width = '100px'; // ✅ Set height to 100px box.style.height = '100px'; console.log(box.style.width); // 👉️ "100px" console.log(box.style.height); // 👉️ "100px"
# Setting width and height has no effect on inline elements
Note that setting the width and height on an inline element, such as a span has no effect.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> span id="box" style="background-color: salmon">Box 1span> script src="index.js"> script> body> html>
And here is our attempt to update the element’s height and width.
Copied!const box = document.getElementById('box'); // ❌ Set width to 100px box.style.width = '100px'; // ❌ Set height to 100px box.style.height = '100px';
If you open your browser, you will see that the element’s width and height are determined by the content area.
# Setting the element’s display to inline-block
To solve this, we can set the element’s display property to inline-block .
Copied!DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> span id="box" style="background-color: salmon; display: inline-block" >Box 1span > script src="index.js"> script> body> html>
And now we can set the element’s width and height.
Copied!const box = document.getElementById('box'); // ✅ Set width to 100px box.style.width = '100px'; // ✅ Set height to 100px box.style.height = '100px';
Some examples use the setAttribute method to update the element’s height and width, however, the setAttribute method overrides the style property completely.
Copied!const box = document.getElementById('box'); box.setAttribute('style', 'width: 100px; height: 100px');
The setAttribute method takes 2 parameters:
- The name of the attribute we want to set on the element.
- The value that should be assigned to the attribute.
If the attribute already exists, the value is updated, otherwise, a new attribute is added with the specified name and value.
So if you use the setAttribute method approach, you are effectively replacing the element’s style attribute value.
This can be very confusing and difficult to debug, so it’s best to set any CSS properties using the style object on the element.
# Set the Width and Height on a Collection of Elements
If you need to set the width and height on a collection of elements, you have to:
- Select the collection of elements.
- Use the for. of method to iterate over the collection.
- Set the width and height using the style.width and style.height property on each element.
Copied!DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> div class="box" style="background-color: salmon">Box 1div> div class="box" style="background-color: salmon">Box 2div> div class="box" style="background-color: salmon">Box 3div> script src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!const boxes = document.querySelectorAll('.box'); for (const box of boxes) box.style.width = '100px'; box.style.height = '100px'; >
We used the document.querySelectorAll method to select all elements with a class of box .
We then used the for. of loop to iterate over the collection and set the width and height properties on each element.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Javascript Reference — HTML DOM Style width Property
The width property in CSS controls width for block-level elements or on elements with absolute or fixed position.
The width property sets or gets the element’s width.
Browser Support
width | Yes | Yes | Yes | Yes | Yes |
Syntax
Return the width property:
object.style.width='auto|length|%|initial|inherit'
Property Values
Value | Description |
---|---|
auto | Let browser decide. Default |
length | Set the width in length units |
% | Set the width in percent of the container element |
initial | Set to default value |
inherit | Inherit from parent element. |
Technical Details
Example
The following code shows how to set the width of an element.
!DOCTYPE html> html> body> !--from w w w .ja v a2 s .c o m--> button type="button" >"myBtn" onclick="myFunction()">test script> function myFunction() < document.getElementById("myBtn").style.width = "300px"; >
The code above is rendered as follows:
Example 3
The following code shows how to change the height and width of an element.
!DOCTYPE html> html> body> !--from www . j av a2s .c o m--> img >"myImg" src="http://java2s.com/style/demo/border.png" width="100" height="132"> br> button type="button" onclick="myFunction()">test script> function myFunction() < document.getElementById("myImg").style.height = "300px"; document.getElementById("myImg").style.width = "300px"; >
The code above is rendered as follows:
Example 4
The following code shows how to get the width of an element:
!DOCTYPE html> html> body> img >"myImg" src="http://java2s.com/style/demo/border.png" style="width:100px;height:132px;"> button type="button" onclick="myFunction()">test !--from w w w . j a va 2 s . c o m--> script> function myFunction() < console.log(document.getElementById("myImg").style.width); >
The code above is rendered as follows:
java2s.com | © Demo Source and Support. All rights reserved.